Sign in to follow this  
Azenris

Confusion, simple task, not working

Recommended Posts

Basically i have my program generally working. i have some variables long double mpos; and here is a section of my code mpos = ((75 / 150) * 70); Now, the logic works fine, and i've tested it on a calc ((75 / 150) * 70) has an answer of 35 but when running the above code im not getting the right answer. I problem is probably simple but i just cant see it myself :/ I also tried changing the long double to double and float

Share this post


Link to post
Share on other sites
You only have integers in your expression. If you want the result to be floating point or double precision you need to work with floats or doubles. i.e. change 75 to 75.0, etc.

Share this post


Link to post
Share on other sites
The error occurs because the result of the first expression (75/150) is 0. That's because 75 and 150 are both integers. It will evaluate to 0.5 which then gets truncated to 0 when the conversion to int takes place.

You can either make the 75 or the 150 a float, or you can cast it to a float:

mpos = ( 75.0/150 ) * 75;
mpos = ( 75/150.0 ) * 75;
mpos = ( static_cast< float >(75)/150 ) * 75;

All three will give you the correct answer of 37.5.

EDIT: see I was beaten yet again. The cast above will work for variables, too:
int main() {

int numerator = 75;
int denominator = 150;
int scalar = 75;

std::cout << ( static_cast< float >(numerator)/denominator ) * scalar;

return 0;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this