C++: scientific、fixed和setprecision

  • 单精度浮点数 (float)
    • 总位数:32 位
    • 符号位:1 位
    • 指数位:8 位
    • 尾数位(有效数字位):23 位
    • 有效数字(精度):大约 6 到 7 位十进制数字

使用iomanip设置了以上(scientific、fixed和setprecision)三个流操纵符后,将会影响它们后面所有的浮点数输出格式,直到更改回来:

1、使用scientific,不设置setprecision:

#include <iostream>
#include <iomanip>

int main()
{
    float f = 123456.789;
    double d = 123456.789;
    long double ld = 123456.789;

    std::cout << std::scientific << f << std::endl;  // 1.234568e+05
    std::cout << std::fixed << f << std::endl;       // 123456.789062
    std::cout << std::scientific << d << std::endl;  // 1.234568e+05
    std::cout << std::fixed << d << std::endl;       // 123456.789000
    std::cout << std::scientific << ld << std::endl; // 1.234568e+05
    std::cout << std::fixed << ld << std::endl;      // 123456.789000
    return 0;
}

2、使用scientific,设置setprecision(3):

生成海报

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注