static_cast由不一致引起的混淆

时间:2021-07-20 02:57:03

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

为什么每当我在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.

当答案是25时,我得到的值不正确26。

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

但是当我在双打中使用静态强制转换时,我得到了正确的答案,即25。

How can the wrong output be explained?

如何解释错误的输出?

2 个解决方案

#1


9  

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

你会期待什么呢?编译器首先评估右侧,然后隐式转换为int。因此,26.0变为26

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

在添加之前进行投射,然后你将添加10和15,结果是25 :)

#2


2  

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.

实际上,在进行自动转换时,您不能依赖浮点数来绕过任何一种方式。如果26.0由26.00005表示,它将四舍五入为26,如果它由25.999995表示,它将四舍五入为25.如果你想确定,请使用math.h中定义的标准C函数round。说这样,26.0变成26就不太正确了。

#1


9  

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

你会期待什么呢?编译器首先评估右侧,然后隐式转换为int。因此,26.0变为26

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

在添加之前进行投射,然后你将添加10和15,结果是25 :)

#2


2  

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.

实际上,在进行自动转换时,您不能依赖浮点数来绕过任何一种方式。如果26.0由26.00005表示,它将四舍五入为26,如果它由25.999995表示,它将四舍五入为25.如果你想确定,请使用math.h中定义的标准C函数round。说这样,26.0变成26就不太正确了。