gpt4 book ai didi

c++ - 标准库 to_string(double) 在 vs2015 中给出了错误的值。有什么解决办法吗?

转载 作者:行者123 更新时间:2023-11-30 00:42:55 25 4
gpt4 key购买 nike

在 Vs2013 to_string 函数 std::to_string(1.0e+30) 中提供输出 1000000000000000000000000000000.000000

在 Vs2015 中,to_string 函数 std::to_string(1.0e+30) 提供输出 1000000000000000019884624838656.000000

如果是标准库问题,是否有可用的修复或补丁?

我搜索了这个问题,遇到一篇文章解释https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/6xhWgsEuvPoto_string 在 float 或 double conversion 中有错误。

double d = 1.0000000000000000e+30;
std::string s = std::to_string(d);
if (s.length())
{
s;
}

这里给定值为 1000000000000000019884624838656.000000

预期结果是 1000000000000000000000000000000.000000,在 vs2013 中给出,但在 vs2015 中没有

最佳答案

按照标准,两者都是“正确”的结果。

There are three floating-point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The value representation of floating-point types is implementation-defined. [ Note: This document imposes no requirements on the accuracy of floating-point operations; see also [support.limits]. — end note ]

VS 2015 结果更常见,因为它符合 IEEE 754 .根据该定义,10000000000000000000000000000000 不可表示,最接近它的可表示数字是 1000000000000000019884624838656

The 53-bit significand precision gives from 15 to 17 significant decimal digits precision.

我对 VS 2013 如何达到 1000000000000000000000000000000000000 感到非常惊讶。参见 the examples at cppreference

关于c++ - 标准库 to_string(double) 在 vs2015 中给出了错误的值。有什么解决办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57371864/

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