Stationary confusion caused by inconsistency

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 am getting the wrong value 26 and the answer is 25.

However, when I use static translations in doubles, I get the correct answer, which is 25.

How to explain the wrong conclusion?

+1


source to share


2 answers


This is absolutely correct.

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 evaluates the right side first and then implicitly converts to int. So it 26.0

becomes26

When you add before adding, you add 10

and 15

, which will lead to 25

:)

+9


source


In fact, you cannot rely on floating point numbers per round anyway for automatic conversions. If 26.0 is represented by 26.00005 it will be rounded to 26, if 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

. The statement So 26.0 becomes 26 is not entirely correct.



+2


source







All Articles