Question

Why whenever I compile and run the following code in Visual Studio 2008:

double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);

I get an incorrect value of 26 while the answer is 25.

However when I use static casts on the doubles, I get the right answer which is 25.

How can the wrong output be explained?

Was it helpful?

Solution

It's absolutely right.

double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2; // int whole_number = 26.0;
Console::WriteLine(whole_number);

What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus, 26.0 becomes 26

When you cast before you add, then you are going to add 10 and 15, which results in 25 :)

OTHER TIPS

Actually, you can not rely on floating point numbers to round of either way when doing an automatic conversion. If 26.0 is represented by 26.00005, it will be rounded to 26, if it is represented by 25.999995, it will be rounded to 25. If you want to be sure, use the standard C function round, defined in math.h. Saying Thus, 26.0 becomes 26 isn't quite correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top