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.
What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus,
26.0becomes26When you cast before you add, then you are going to add
10and15, which results in25🙂