Understanding the order of operations in C++

Hi,

I'm a little confused about the way C++ handles the order of operations, it seems to be different. For instance I have the following calculation which to me should be 8 ...

((20 / 150)*60) = 8

... but when I do it in C++ I get 0, why?

float total = ((20 / 150)*60); // this outputs 0, why?

See the C++ calculation here
http://ideone.com/PbaZcp

Can some be so kind and explain me why do I get different results when working with C++?

Thanks
Last edited on
The order of operations is correct in C++. The problem with that statement is that it divides the integer "20" by the integer "150", which returns an integer. And an integer can't contain decimals. You have to tell C++ that the result should be stored in a float. Simply declaring the variable to be of type "float" doesn't do anything.

If you type in "(20 / 150.0f) * 60" it will give you the expected result of 8.

You can also type in "(20 / (float) 150) * 60" and it will give you the expected result.

1
2
3
float total = (20 / 150.0f) * 60; // No need for the brackets around it
// or
total = (20 / (float) 150) * 60; // I prefer the first one 
(20 / 150) is an integer operation because 20 and 150 are both considered to be int, and so the result will be 0.

To make it a floating point operation, at least one of the operands must be float.
This means either 20 or 150 must be marked as float.

Here's a simple solution:

float total = ((20.0f / 150)*60);

As for the order of operations:
http://en.cppreference.com/w/cpp/language/operator_precedence

You may also want to look into Literals:
http://en.cppreference.com/w/cpp/language/floating_literal
the integer literals 20, 150, and 60 as they are are interpreted as ints. 20/150 is .13, which will be truncated to 0 as an int. 0 * 60 is 0.

You need to change the literals so that the compiler knows you're using floats.
float total = ((20.0 / 150.0) * 60.0); // computes 8
http://ideone.com/jshcdV

EDIT:
Beat to the punch
Last edited on
Got it, thanks a lot for the good explanation, it now make sense.
Topic archived. No new replies allowed.