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.
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.
7/9*9
equals (7 / 9) * 9
, but as 7
and 9
are integers and not floating point numbers, 7 / 9
equals 0 (the quotient of the division).
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;
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
.