views:

440

answers:

6

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.

+29  A: 

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.

Jacob
Haha! Its awesome how the super simple questions become a sniping contest. Well explained though.
Kai
wow, 11 upvotes in 1 min
Matt
I know .. haha, pays to check out SO when you're wrestling with a bug :D
Jacob
too bad for programmers in the other part of the world (asia), we can't catch up with sniping low-hanging-fruit questions :-)
Hao
Haha, well put :)
Jacob
+6  A: 

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.

Kai
Strictly, with floats, there's still a discarded remainder. IOW there's a roundoff error. Pedantically, division is the inverse of multiplication, which isn't possible for all integers or all floats. By definition, approx-quotient + (remainder * divisor) = dividend, where approx-quotient means the result from the division algorithm. There is a remainder with floating point and fixed point division as well as integers - though hardly anyone cares about its exact value, so don't expect an operator for it.
Steve314
Thanks for mentioning that Steve! Small fast responses tend to miss subtle but important details like that.
Kai
+3  A: 

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

Pierre Bourdon
+5  A: 

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;
R Samuel Klatchko
+2  A: 

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;

RAC
+1  A: 

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.

Adisak