cout输出指定位数的浮点数
cout输出指定位数的浮点数。
//方便快速复制
#include <iomanip>
cout << std::fixed << std::setprecision(2);
cout << std::defaultfloat;
浮点精度更改
指定输出小数点后几位,包含在<iomanip>头文件中
#include <iostream>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
int main(int argc, char* argv[]){
    double a = 1.6006;
    cout << std::setprecision(2) << a << endl;
    return 0;
}
输出:
1.6
单独使用并不会进行补0操作
浮点数格式化
对于浮点数输入/输出的默认格式化,有四个操纵符可对其修改:
- std::fixed:使用定点操纵浮点数
- std::scientific:使用科学计数法操纵浮点数
- std::hexfloat:使用十六进制操纵浮点数
- std::defaultfloat:使用默认的浮点数操纵方式
十六进制浮点格式化忽略流精度规定
包含在头文件<ios>中,而头文件<ios>包含在<iostream>中。
#include <iostream>
#include <sstream>
 
void print(const char* textNum, double num)
{
    std::cout << "The number " << textNum << " in fixed:      " << std::fixed << num << '\n'
              << "The number " << textNum << " in scientific: " << std::scientific << num << '\n'
              << "The number " << textNum << " in hexfloat:   " << std::hexfloat << num << '\n'
              << "The number " << textNum << " in default:    " << std::defaultfloat << num << '\n';
}
 
int main()
{
    print("0.01   ", 0.01);
    print("0.00001", 0.00001);
    double f;
    std::istringstream("0x1P-1022") >> std::hexfloat >> f;
    std::cout << "Parsing 0x1P-1022 as hex gives " << f << '\n';
}
输出:
//十六进制输出结果因人而异,无精度可言
The number 0.01    in fixed:      0.010000
The number 0.01    in scientific: 1.000000e-02
The number 0.01    in hexfloat:   0x1.47ae147ae147bp-7
The number 0.01    in default:    0.01
The number 0.00001 in fixed:      0.000010
The number 0.00001 in scientific: 1.000000e-05
The number 0.00001 in hexfloat:   0x1.4f8b588e368f1p-17
The number 0.00001 in default:    1e-05
Parsing 0x1P-1022 as hex gives 2.22507e-308
参考文章
std::fixed, std::scientific, std::hexfloat, std::defaultfloat