954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

c++ math help

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;
the_kitoper
Newbie Poster
7 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

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

thines01
Postaholic
Team Colleague
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
 
float RoD = 0.5;

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

the_kitoper
Newbie Poster
7 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

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 ?

ravenous
Posting Pro
516 posts since Jul 2005
Reputation Points: 269
Solved Threads: 92
 

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

Your code:

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.

LRRR
Junior Poster in Training
55 posts since Dec 2011
Reputation Points: 22
Solved Threads: 15
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: