gpt4 book ai didi

c++ - 如何在 C++ 中以浮点/ double 值表示无穷大?

转载 作者:行者123 更新时间:2023-12-05 01:31:38 49 4
gpt4 key购买 nike

作为cppreference说“在 IEEE 754 中, float 最常见的二进制表示形式,正无穷大是指数的所有位都已设置且小数的所有位都已清除的值。”。我试过这个代码片段,但我没有看到指数位设置。我哪里错了吗?

#include <iostream>
#include <limits>
#include <bitset>
#include <math.h>
using namespace std;
int main() {
float a = 0b00000000000000000000000000000000;

double b = std::numeric_limits<double>::infinity();
bitset<64> x(b);

cout<<x<<endl;
return 0;
}

它在控制台上打印 0000000000000000000000000000000000000000000000000000000000000000。

最佳答案

std::bitset 没有接受 double 的构造函数。当您传递 double 时,您改为调用接受 unsigned long long 的构造函数,并且 double 首先隐式转换为 unsigned long long

问题是,unsigned long long 不能表示无穷大,因此程序的行为是未定义的。标准说:

[conv.fpint]

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.


要查看位,您可以先将浮点“位转换”为整数类型,然后将该整数传递给 bitset:

auto int_b = std::bit_cast<std::uint64_t>(b);
std::bitset<64> x(int_b);

关于c++ - 如何在 C++ 中以浮点/ double 值表示无穷大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66049285/

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