gpt4 book ai didi

c++ - 为什么 std::cout 将 4.9999999 打印为 5?

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:54 24 4
gpt4 key购买 nike

我正在使用这段代码找出 log(3)log10(3) 之间的区别:

void testPrecisionError() {
cout
<< log(243) / log(3) << " : "
<< int(log(243) / log(3)) << " : "
<< endl;

cout
<< log10(243) / log10(3) << " : "
<< int(log10(243) / log10(3)) << " : ")
<< endl;
}

输出是:

5 : 4  // I think it is 4.999999 underlying
5 : 5

我发现 4.999999 被打印为 5

为什么 C++ 不像 Java 那样将其打印为 4.99999

我想我无法再cout 说服自己没有精度损失!

最佳答案

因为它四舍五入到所请求精度的最后一位最接近的值。实际值约为:

4.99999999999999911182158029987

对于 6 位精度,它比 4.999999 更接近 5.000000,因此它显示 5。如果您使用 setprecision(16) 或更高版本,您将看到所有 9。

当您转换为 int 时,它总是会截断,不会四舍五入到最接近的值。

至于为什么 Java 显示为 4.999999,也许它只是丢弃了多余的数字而不是四舍五入。

关于c++ - 为什么 std::cout 将 4.9999999 打印为 5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38406880/

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