从大双精度数静态转换为整数时的奇怪行为
这是我的简单代码:
int main() {
double d1 = 10000000000.0;
const double d2 = 10000000000.0;
cout << static_cast<int>(d1) << endl;
cout << static_cast<int>(d2) << endl;
cout << static_cast<int>(10000000000.0) << endl;
}
输出是:
-2147483648
2147483647
2147483647
这让我非常惊讶。为什么正 double 有时会被转换为负 int?
我正在使用 g++:GCC 版本 4.4.3(Ubuntu 4.4.3-4ubuntu5)。
Here 's my simple code:
int main() {
double d1 = 10000000000.0;
const double d2 = 10000000000.0;
cout << static_cast<int>(d1) << endl;
cout << static_cast<int>(d2) << endl;
cout << static_cast<int>(10000000000.0) << endl;
}
The output is:
-2147483648
2147483647
2147483647
This surprised me grealy. Why would a positive double sometimes get casted to a negative int?
I'm using g++
: GCC version 4.4.3 (Ubuntu 4.4.3-4ubuntu5).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
int
不足以容纳该值时,将double
转换为int
会产生未定义的行为。此行为源自 C:
对您来说,
int
显然不够大。但不要依赖此代码中的任一(或者实际上任何)行为。
Casting a
double
to anint
whenint
isn't big enough to hold the value yields undefined behaviour.This behaviour is derived from C:
For you,
int
clearly isn't big enough.But don't rely on either (or, indeed, any) behaviour in this code.
来自 C 标准(1999):
6.3.1.4 实数浮点数和整数
1 当实浮点类型的有限值转换为_Bool以外的整数类型时,
小数部分被丢弃(即,该值被截断为零)。如果值
整数部分不能用整数类型表示,行为未定义。
来自 C++ 标准 (2003):
4.9 浮点积分转换 [conv.fpint]
1 浮点类型的右值可以转换为整数类型的右值。转换截断;
即小数部分被丢弃。如果不能截断值,则行为未定义
以目标类型表示。 [注:如果目标类型为 bool,请参见 4.12。 ]
很可能你的 double 太大而无法正确转换为 int。
From the C standard (1999):
6.3.1.4 Real floating and integer
1 When a finite value of real floating type is converted to an integer type other than _Bool,
the fractional part is discarded (i.e., the value is truncated toward zero). If the value of
the integral part cannot be represented by the integer type, the behavior is undefined.
From the C++ standard (2003):
4.9 Floating-integral conversions [conv.fpint]
1 An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates;
that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be
represented in the destination type. [Note: If the destination type is bool, see 4.12. ]
Most likely your double is too big to be converted correctly to int.