为什么cout的输出<< 7/9*9;是零吗?
为什么下面代码的输出等于0或served?
cout << 7/9*9; //output 0 (zero) why?
float nine = 9;
float seven = 7;
float i = seven/nine*nine;
cout << i //output 7 Why?
感谢您的帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
7/9*9 将这些数字计算为整数,因此 7/9 计算结果为 0,并且 0*9 = 0。
当您将它们设置为浮点数时,您正在执行预期的计算。
尝试 7.0/9*9 得到 7,然后您将进行浮点运算。
7/9*9 evaluates those numbers as integers, so 7/9 evaluates to 0, and 0*9 = 0.
When you made them floats, you were performing the intended calculation.
Try 7.0/9*9 to get 7, and then you'll be doing a floating point operation.
在 C 语言中,当你除以整数时,余数会被丢弃。在这里,您正在执行 7 / 9,然后将其结果乘以 9。在步骤中,C 的想法如下:
当您使用浮点数时,它可以正常工作,因为余数不再被丢弃。
In C, when you divide integers, the remainder gets discarded. Here, you're doing 7 / 9, then taking the result of that and multiplying by 9. In steps, heres what C thinks:
When you use floats it works properly because the remainder is no longer discarded.
在:
你正在做整数算术。所以 7/9 是 0,0*9 是 0。
要使用浮点算术(这就是您在第二个示例中使用的),您需要执行以下操作:
In:
you are doing integer arithmetic. So 7/9 is 0 and 0*9 is 0.
To use floating point arithmetic (which is what you are using in your second example), you want to do:
7/9*9
等于(7 / 9) * 9
,但由于7
和9
是整数,非浮点数,7 / 9
等于 0(除法的商)。7/9*9
equals(7 / 9) * 9
, but as7
and9
are integers and not floating point numbers,7 / 9
equals 0 (the quotient of the division).我认为这是一个精度问题。 / 和 * 运算符的优先级相同,因此 7/9*9 从左到右计算为 (7/9)*9。问题是 (7/9) 在整数算术中是 0。当您将它们显式存储为浮点数时,该 / 操作将以浮点形式完成,它可以比 int 更高精度地存储 7/9。
如果您想在一行中进行计算而不存在精度问题,请尝试:
cout << 7.0f/9.0f*9.0f;
I think it's a precision issue. The / and * operators are equal precedence, so 7/9*9 is evaluated left to right at as (7/9)*9. The catch is that (7/9) is 0 in integer arithmetic. When you explicity store them as floats, that / operation is done in floating point, which can store 7/9 with greater precision than an int.
If you want to do the calculation in one line without the precision issue, try:
cout << 7.0f / 9.0f * 9.0f;
已经有很多正确答案了。附加说明:如果您想将其保留为整数运算而不使用浮点,则需要对其进行排序,以便在除法之前进行乘法以获得最高精度(只要在乘法期间不发生溢出)。因此比将转换为浮点数的
(7.0/9)*9
,您可以执行(9*7)/9
。Many correct answers already. An addition note: if you want to leave this as an integer operation and not use floating point, you want to order it so you do multiplies before divides to get the most precision (as long as overflow doesn't occur during multiplication. Thus rather than
(7.0/9)*9
which will convert to floats, you can do(9*7)/9
.