C++格式化输出小数点后位数

来源:互联网 发布:数据库设计用什么软件 编辑:程序博客网 时间:2024/05/20 22:39

C++格式化输出小数点后位数

C语言中可以用 printf(“%.2lf\n”, num); 输出指定位数的浮点数,那么C++输出指定位数浮点数的方法是:

#include <iostream>using std::ios;using std::cin;using std::cout;using std::endl;int main(void){    double PI = 3.1415926535;    cout << "PI=" << PI << endl;    cout.setf(ios::fixed);    cout.setf(ios::showpoint);    cout.precision(2);    cout << "PI=" << PI << endl;    cout.setf(ios::fixed);    cout.setf(ios::showpoint);    cout.precision(6);    cout << "PI=" << PI << endl;    return 0;}

运行结果
值得注意的是,如果在程序中添加了

    cout.setf(ios::fixed);    cout.setf(ios::showpoint);    cout.precision(2);

那么其后所有的`cout 语句在输出浮点数时都将保留有小数点后2位,其中2可以用任何非负数代替

( 标记ios::fixed使流按照定点符号的形式输出浮点数。该形式是我们平时书写数字的一种格式。如果已经通过调用set()函数设置了标记ios::fixed,那么所有的浮点数都将按照我们习惯的格式输出,而不是按照科学计数法的格式输出。  标记ios::showpoint使流在输出浮点数时总是包含小数点)