gpt4 book ai didi

c++ - C++(和 C)类型转换期间明显不一致

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

任何人都可以解释这里的输出吗?我一直试图理解为什么在这段代码中对文字进行类型转换的结果与对变量进行类型转换的结果不同。

#include <iostream>
#include <cstdint>

using namespace std;

int main()
{
double intermediate;
intermediate = -1.0;
cout << "intermediate = " << intermediate << endl;
cout << "uint64_t(intermediate) = " << uint64_t(intermediate) << endl;
cout << "uint64_t((double)(-1)) = " << uint64_t((double)(-1)) << endl;

return 0;
}

我得到的输出是:

intermediate = -1                                                                                                                                   
uint64_t(intermediate) = 18446744073709551615
uint64_t((double)(-1)) = 0

最佳答案

您正在执行从浮点类型到整数类型的越界转换。

由于 double 值 -1.0 无法放入 uint64_t,因此这被视为超出范围的转换。这样的转换调用 undefined behavior 。这意味着,除其他外,两次转换尝试不必产生相同的结果。

请注意,这与有符号整数到无符号整数的转换不同,后者在所有情况下都有明确定义。

这是由 C++17 standard 的 7.10p1 规定的:

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.

C11 standard 第 6.3.1.4p1 节有类似的语言:

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. 61)

...

61) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (−1,Utype_MAX+1)

为了获得一致的结果,您首先需要转换为有符号整数类型,然后转换为无符号类型。

cout << "uint64_t(intermediate) = " << 
static_cast<uint64_t>(static_cast<int>(intermediate)) << endl;

对于C:

printf("uint64_t(intermediate) = %llu\n", (uint64_t)(int)intermediate);

关于c++ - C++(和 C)类型转换期间明显不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60241616/

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