Public Group

# Confusion, simple task, not working

This topic is 4628 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 on other sites
Try this:
long double mpos;mpos = ((75.0f / 150.0f) * 70.0f);

See if that works.

Maybe its because it doesnt recognize it as a float or something... [smile]

##### 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 on other sites
mpos = ((75.0f / 150.0f) * 70.0f); worked :)

but, the 75 and 150 are examples, i intend to put variables there too, but from your replies i get the problem i had. Thnx :D

##### 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 on other sites
Always nice to see more than one method, thnx all :)

1. 1
2. 2
3. 3
4. 4
5. 5
Rutin
17

• 10
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631420
• Total Posts
2999987
×