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?
-
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
becomes26
When you cast before you add, then you are going to add
10
and15
, which results in25
:) -
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 inmath.h
. Saying Thus, 26.0 becomes 26 isn't quite correct.Johannes Schaub - litb : if it *is* 26.0, then it will become 26. that's quite right. but if it is 25.999995, as you say, it is 25, as you also say.Johannes Schaub - litb : nevertheless, you are right in principle indeed. static_cast(val + 0.5) fixes that concerns. (round is c99, not available in c++)
0 comments:
Post a Comment