gpt4 book ai didi

c++ - 将负 const double 转换为 unsigned 结果为 0 而 non-const double 很好

转载 作者:行者123 更新时间:2023-12-04 00:12:51 25 4
gpt4 key购买 nike

我有这个代码:

#include <iostream>

int main() {
double val = -400.0;
const double constVal = -400.0;
std::cout << val << std::endl;
std::cout << static_cast<unsigned>(val) << std::endl;
std::cout << constVal << std::endl;
std::cout << static_cast<unsigned>(constVal) << std::endl;

return 0;
}

当我运行它时,这是输出:

-400
4294966896
-400
0

为什么会这样?适度的谷歌搜索在这件事上没有显示任何内容。

最佳答案

来自 cppreference.com :

A prvalue of floating-point type can be converted to a prvalue of anyinteger type. The fractional part is truncated, that is, thefractional part is discarded. If the value cannot fit into thedestination type, the behavior is undefined (even when the destinationtype is unsigned, modulo arithmetic does not apply). If thedestination type is bool, this is a boolean conversion (see below).

-400 不适合 unsigned,因此行为未定义。试图推理任何类型的一致性都是无用的。

由于这是未定义的行为,编译器可以在这种情况下做任何事情。通常,他们会做任何使他们(定义的)行为的其余部分更容易编码的事情。尽管 popular sayings ,编译器不太可能让恶魔飞出你的 Nose ,但人们不应该特别期待任何行为。

关于c++ - 将负 const double 转换为 unsigned 结果为 0 而 non-const double 很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67336264/

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