简体   繁体   English

为什么cout的输出<< 7/9 * 9; 是零?

[英]Why is the output of cout << 7/9*9; is zero?

Why is the output of the following code equals to 0 or serven? 为什么以下代码的输出等于0或serven?

cout << 7/9*9;   //output 0 (zero)   why?

float nine = 9;
float seven = 7;
float i = seven/nine*nine;
cout << i     //output 7   Why?

Thanks for the help. 谢谢您的帮助。

7/9*9 evaluates those numbers as integers, so 7/9 evaluates to 0, and 0*9 = 0. 7/9 * 9将这些数字评估为整数,因此7/9的计算结果为0,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. 尝试7.0 / 9 * 9得到7,然后你将进行浮点运算。

In C, when you divide integers, the remainder gets discarded. 在C中,当您对整数进行除法时,其余部分将被丢弃。 Here, you're doing 7 / 9, then taking the result of that and multiplying by 9. In steps, heres what C thinks: 在这里,你正在做7/9,然后取结果并乘以9.在步骤中,接下来是C的想法:

7 / 9 = 0
0 * 9 = 0

When you use floats it works properly because the remainder is no longer discarded. 使用浮动时,它可以正常工作,因为其余部分不再被丢弃。

In: 在:

cout << 7 / 9 * 9;

you are doing integer arithmetic. 你正在做整数运算。 So 7/9 is 0 and 0*9 is 0. 所以7/9是0而0 * 9是0。

To use floating point arithmetic (which is what you are using in your second example), you want to do: 要使用浮点运算(这是您在第二个示例中使用的),您要执行以下操作:

cout << 7.0 / 9 * 9;

7/9*9的equals (7 / 9) * 9 ,但作为79是整数,并且不浮点数, 7 / 9等于0(除法的商)。

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. /和*运算符的优先级相同,因此7/9 * 9从左到右依次为(7/9)* 9。 The catch is that (7/9) is 0 in integer arithmetic. 问题是(7/9)在整数运算中为0。 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. 当你明确地将它们存储为浮点数时,/操作是以浮点形式完成的,它可以以比int更高的精度存储7/9。

If you want to do the calculation in one line without the precision issue, try: 如果要在没有精度问题的情况下在一行中进行计算,请尝试:

cout << 7.0f / 9.0f * 9.0f; cout << 7.0f / 9.0f * 9.0f;

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 . 附加说明:如果要将其保留为整数运算而不使用浮点,则需要对其进行排序,以便在除数之前进行乘法以获得最高精度(只要在乘法过程中不发生溢出。比(7.0/9)*9将转换为浮点数,你可以做(9*7)/9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM