I have a problem, whenever I attempt to use the following expression it returns -3.
Can you please explain why this is?

``````int level = ((RoD * 10) - 50) / 15;
std::cout << "Level = " << level << std::endl;``````

You would get that value if RoD is ZERO ( 0 ).

``float RoD = 0.5;``

Could it be that the equation is default-based on integer arithmetic?

I don't understand, -3 is the correct answer if `RoD` is 0.5. Do you get -2.666... if you set `RoD = 1.0` ?

If you cout these two, you will understand what is the difference between 1.0 and 1.

``````std::cout << ((1 * 10) - 50) / 15 << std::endl; // -2
std::cout << ((1.0 * 10) - 50) / 15 << std::endl;  // -2.66667``````

``````float RoD = 0.5;
int level = ((RoD * 10) - 50) / 15;
std::cout << "Level = " << level << std::endl;``````

RoD is a float, it will be treated as a floating point number.
(0.5 * 10) = 5.0, then ( 5.0 - 50 ) => -45.0, -45.0 / 15 => -3 when it gets assigned to an int, you loose all the floating point precision, it gets truncated, that's why you get -3 instead of -3.0.

An example:

``````float RoD = 1.55;
int level = ((RoD * 10) ) * 3;
std::cout << "Level = " << level << std::endl;``````

RoD * 10 => 1.55 * 10 = 15.5
After the multiplication of RoD and 10, if you multiply the result with 3 you would get : 15.5 * 3 = 46.5
If it wouldn't be treated as a floating point number, you would get 45 instead of 46.5. Cout 'level',and you will see it holds the value 46, which proves you had a floating point number until it got assigned to level(int), but it got truncated.

Hope it's not too confusing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.