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

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

+4
source share
6 answers

7/9 * 9 evaluates these numbers as integers, so 7/9 evaluates 0 and 0 * 9 = 0.

When you made them floating, you performed the planned calculation.

Try 7.0 / 9 * 9 to get 7, and then you will perform a floating point operation.

+31
source

In C, when you divide integers, the remainder is discarded. Here you do 7/9 and then take the result and multiply by 9. In steps, as C thinks:

 7 / 9 = 0 0 * 9 = 0 

When you use float, it works correctly, because the remainder is no longer discarded.

+6
source

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 you use in your second example), you want:

 cout << 7.0 / 9 * 9; 
+5
source

7/9*9 is (7 / 9) * 9 , but since 7 and 9 are integers and not floating point numbers, 7 / 9 is 0 (quotient from division).

+3
source

I think this is a problem of accuracy. The operators / and * have the same priority, so 7/9 * 9 is evaluated from left to right with (7/9) * 9. The catch is that (7/9) is 0 in integer arithmetic. When you explain them as a float, this operation is performed in floating point, which can store 7/9 with more precision than int.

If you want to perform calculations on one line without error, try:

cout <7.0f / 9.0f * 9.0f;

+2
source

Already a lot of correct answers. Note: if you want to leave this as an integer operation and not use a floating point, you want to order it to multiply it before division, in order to get maximum accuracy (until overflow happens during multiplication. Than (7.0/9)*9 , which converts to float, you can do (9*7)/9 .

+1
source

All Articles