C++ 保留几位小数

来源:互联网 发布:av 女程序员 编辑:程序博客网 时间:2024/04/27 17:25

#include<iostream>
#include<iomanip>   //头文件不可少
using namespace std;

int main()
{
      double a = 3.14159;
      cout << setiosflags(ios::fixed) << setprecision(0) << a << endl;  //保留0位小数
      cout << setiosflags(ios::fixed) << setprecision(1) << a << endl;  //保留1位小数
      cout << setiosflags(ios::fixed) << setprecision(2) << a << endl;  //保留2位小数
      cout << setiosflags(ios::fixed) << setprecision(3) << a << endl;  //保留3位小数,不仅仅截断字符,还可以四舍五入
      cout << setiosflags(ios::fixed) << setprecision(4) << a << endl;  //保留4位小数
      cout << setiosflags(ios::fixed) << setprecision(5) << a << endl;  //保留5位小数
      cout << setiosflags(ios::fixed) << setprecision(6) << a << endl;  //保留6位小数
      return 0;
}

输出:


0 0
原创粉丝点击