C++设置输出小数位数方法

浮点数的输出一共有三种模式:普通、固定小数、科学记数法
后两种分别对应格式标记 ios::fixed, ios::scientific 。都不设的话就是普通模式,即自动选择小数或科学记数法(看哪种占用宽度小)
设定后两种模式需要用 fstream 的成员函数 fout.setf(flag)
要固定2位小数,只要选择 fixed 模式并设定精度为 2 即可,

另外,ios::showpoint 根据精度设置显示小数点和末尾的零

          cout.width() 设置输出字段的宽度《21天学通C++》P435;

#include<fstream>
using namespace std;
int main(){
    ofstream fout("out.txt");
    fout.setf(ios::fixed, ios::floatfield);  // 设定为 fixed 模式,以小数点表示浮点数
    fout.precision(2);  // 设置精度 2

你可能感兴趣的:(C++设置输出小数位数方法)