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?
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
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