Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I was working with Visual Studio 2005 on a relatively simply problem, but it was fairly heavy in mathematical calculations. However, my program simply was not giving me the correct output and I could not figure out why. Long story short, I found out it was because I was basically doing this:

double x = 2/5;

However, I eventually found out that the compiler was turning that into 0 instead of .4! If I entered...

double x = .4;

Then it worked correctly. Is this an issue that was fixed in more recent Visual Studios, or what? I was extremely disappointed (yet also relieved since the program was so simple yet I was unable to do it!) when I figured out that it was as simple as a "fraction" being set to 0 instead of being divided out.
Posted
Updated 3-May-10 20:19pm
v2

1 solution

This is an issue with the C++ standard. The compiler is doing EXACTLY what you ask of it.

2/5

is the same as

(int)2/(int)5

So, the result that is returned, is an int, which is THEN turned into a double.

2/(double)5 or
2/5.0

will work fine.
 
Share this answer
 
Comments
slapshot6819 4-May-10 1:12am    
Thanks for the response, very informative. Interesting. Interesting, but annoying. I rewrote my code and redid the math multiple times before I finally found out the problem heh...
Emilio Garavaglia 7-May-10 7:50am    
Welcome to the C++ enigmistics!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900