format lon-6ren">
gpt4 book ai didi

c++ - 为什么 std::setprecision 显示不存在的精度位以及如何查看真正的 float

转载 作者:行者123 更新时间:2023-11-27 23:48:53 24 4
gpt4 key购买 nike

我希望看到 float 和 double 内容,但我得到了很多额外的意想不到的精度数字。

printf("%.55f\n", 1.123456789012345);
cout << setprecision(100) << 1.123456789012345 << endl;

1.1234567890123450251138592648203484714031219482421875000 1.1234567890123450251138592648203484714031219482421875

当我期待这样的事情时:

1.12345678901234500...
1.123456789012345

在 Octave 中我也得到了意想不到的输出:

>> format long
>> single(1.123456789012345)
ans = 1.12345683574677

最佳答案

I would like to see float and double content

您实际上正在观察最接近 1.123456789012345 的十进制数,它可以完全由浮点表示法表示。请注意,1 等其他一些十进制数可以用浮点表示法精确表示。

因此,运行:

std::cout << std::setprecision(100) << 1.123456789012345 << std::endl;
std::cout << std::setprecision(100) << 1.0 << std::endl;
std::cout << std::setprecision(100) << 1.1 << std::endl;
std::cout << std::setprecision(100) << 1.5 << std::endl;

将打印:

1.1234567890123450251138592648203484714031219482421875
1
1.100000000000000088817841970012523233890533447265625
1.5

我强烈推荐阅读 David Goldberg 的优秀 What Every Computer Scientist Should Know About Floating-Point Arithmetic

关于c++ - 为什么 std::setprecision 显示不存在的精度位以及如何查看真正的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48283055/

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