C++ 中的除法未按预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6101084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Division in C++ not working as expected
提问by Psirus
I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
我在做别的事情,但结果都是零,所以我做了这个简约的例子,输出仍然是 0。
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
我错过了什么?
回答by
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
你错过了 3 和 5 是整数的事实,所以你得到了整数除法。要使编译器执行浮点除法,请将其中之一设为实数:
double f = 3.0 / 5;
回答by leftaroundabout
It doesn't needto be .0
, you can also do 3./5
or 3/5.
or 3e+0 / 5
or 3 / 5e-0
or 0xCp-2 / 5
or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.
它不需要是.0
,你也可以做3./5
or 3/5.
or 3e+0 / 5
or 3 / 5e-0
or 0xCp-2 / 5
or... 只需要涉及一个指标,这样编译器就知道它应该将除法作为浮点执行。
Another possibility: double f=double(3)/5
. That's much more typing, but it leaves no doubt to what you are doing.
另一种可能:double f=double(3)/5
。这是更多的打字,但它毫无疑问你在做什么。
Or simply use double f=.6
, that also does the trick...
或者简单地使用double f=.6
,这也可以解决问题......
回答by sergio
try this:
尝试这个:
double f = 3.0/5.0;
this should fix your problem
这应该可以解决您的问题
回答by Diego Sevilla
Try putting a .0
after one of the divisors. This will convert them into floating point literals.
尝试.0
在其中一个除数之后放置 a 。这会将它们转换为浮点文字。
回答by Joe Tyman
You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.
您正在使用整数。你可以做很多事情来让你的常量像 leftaroundabout 状态一样加倍,但这不是很好。它很难阅读和混淆。如果您想要 3 和 5,请将它们设为 3.0 和 5.0。如果他们被迫阅读您的代码,每个人都会知道您的意思。他/她所说的大部分内容确实需要您了解 C/C++ 以及浮点数如何存储以产生正面或反面。
回答by F?rid Alijani
In case, you save your generic variables with int
and would like to obtain the ratio as double
:
如果您保存通用变量int
并希望获得比率为double
:
using namespace std;
int main()
{
int x = 7;
int y = 4;
double ratio;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
}