gpt4 book ai didi

c++ - 从大 double 静态转换为整数时的奇怪行为

转载 作者:可可西里 更新时间:2023-11-01 16:02:46 25 4
gpt4 key购买 nike

这是我的简单代码:

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 有时会转换为负整数?

我正在使用 g++:GCC 版本 4.4.3 (Ubuntu 4.4.3-4ubuntu5)。

最佳答案

int 不足以容纳值时,将 double 转换为 int 会产生未定义的行为.

[n3290: 4.9/1]: A prvalue of a floating point type can be converted to a prvalue 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.

此行为源自 C:

[C99: 6.3.1.4/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.

对你来说,int 显然不够大。

  • 并且,在第一种情况下,对于您来说,这恰好导致符号位被设置。
  • 对于您来说,在第二种和第三种情况下,可能恰好是优化导致了不同的行为。

但不要依赖此代码中的任一个(或者实际上任何)行为。

关于c++ - 从大 double 静态转换为整数时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7703575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com