c++ - 为什么 cout.precision() 会增加 float 的精度?

标签 c++ floating-point precision cout

据我所知,单个 float 的精度约为 6 位,因此以下程序将输出 2 也就不足为奇了。 .

#include<iostream>
using namespace std;

int main(void) {
    //cout.precision(7);

    float f = 1.999998; //this number gets rounded up to the nearest hundred thousandths
    cout << f << endl;  //so f should equal 2

    return 0;
}

但是当cout.precision(7)包括在内,实际上在cout << f << endl;之前的任何地方, 程序输出整个 1.999998 .这只能意味着 f存储整个 float 而不四舍五入,对吧?

我知道cout.precision()不应该以任何方式影响浮点存储。这种行为有解释吗?或者它只是在我的机器上?

最佳答案

I understand that single floating-point numbers have the precision of about 6 digits

大约 六位十进制数字,或恰好 23 位二进制数字。

this number gets rounded up to the nearest hundred thousand

不,它没有。它四舍五入到最接近的 23 位二进制数字。不是一回事,不能与之相提并论。

Why does cout.precision() increase floating-point's precision?

事实并非如此。它会影响它的打印方式。

关于c++ - 为什么 cout.precision() 会增加 float 的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43779599/

相关文章:

c++ - boost program_options : using zero-parameter options multiple times?

c++ - set<Vec3b> 的错误行为

java - 浮点运算 = 从 Dec 到 Binary 的最差精度/差异是多少?

c# - 哪种方式更准确?

c++ - 边缘检测 - 不良检测

c++ - 如何以与此函数相同的方式获取这些参数?

PHP Printf 作为浮点精度

javascript - 如何在javascript中处理大数字

c - 如何在 C 中将 float 转换为字符串而不丢失用户输入的精度?

math - float 学有问题吗?