static_cast 不一致导致混乱
为什么每当我在 Visual Studio 2008 中编译并运行以下代码时:
double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);
我得到错误的值 26,而答案是 25。
但是,当我对双打使用静态强制转换时,我得到正确的答案,即 25。
错误怎么可能输出解释一下?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是绝对正确的。
你会期待什么? 编译器首先计算右侧,然后隐式转换为 int。 因此,
26.0
变为26
当您在添加之前进行强制转换时,您将添加
10
和15
,结果是25
:)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.0
becomes26
When you cast before you add, then you are going to add
10
and15
, which results in25
:)实际上,在进行自动转换时,您不能依靠浮点数进行舍入。 如果26.0用26.00005表示,就会四舍五入到26,如果用25.999995表示,就会四舍五入到25。如果想确定的话,使用标准C函数
round
,定义在 math.h 中。 说因此,26.0 变成 26 并不完全正确。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.