尽管存储为双精度数,为什么除法 (3/5) 结果为零?
我正在做其他事情,但所有结果都是零,所以我做了这个简约的例子,输出仍然是 0。
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
我错过了什么?
I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您忽略了 3 和 5 是整数这一事实,因此您得到的是整数除法。要使编译器执行浮点除法,请将其中之一设为实数:
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:
它不需要是
.0
,您也可以使用3./5
或3/5.
> 或3e+0 / 5
或3 / 5e-0
或0xCp-2 / 5
或...只需要一个涉及的指示器,以便编译器知道它应该以浮点方式执行除法 观点。另一种可能性:
double f=double(3)/5
。打字量要大得多,但毫无疑问你在做什么。或者简单地使用
double f=.6
,这也能达到目的......It doesn't need to be
.0
, you can also do3./5
or3/5.
or3e+0 / 5
or3 / 5e-0
or0xCp-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.Another possibility:
double f=double(3)/5
. That's much more typing, but it leaves no doubt to what you are doing.Or simply use
double f=.6
, that also does the trick...试试这个:
这应该可以解决你的问题
try this:
this should fix your problem
尝试在除数之一后面添加
.0
。这会将它们转换为浮点文字。Try putting a
.0
after one of the divisors. This will convert them into floating point literals.如果您使用
int
保存通用变量,并希望获得double
的比率:In case, you save your generic variables with
int
and would like to obtain the ratio asdouble
:您正在使用整数。您可以通过很多方法使常量加倍,例如 leftaroundabout 状态,但这并不是很好。它很难阅读并且令人困惑。如果您想要 3 和 5,请将它们设为 3.0 和 5.0。如果他们被迫阅读你的代码,每个人都会明白你的意思。他/她所说的大部分内容确实需要您了解 C/C++ 以及如何存储浮点数来得出正面或反面。
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.