简体   繁体   中英

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

Why is the output of the following code equals to 0 or 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.

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.

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:

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.

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. 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;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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