加句system("pause");在return 0;前面就可以了
C++中的cout.setf()、cout.precision(),ostream成员函数里面的,也可以用输出流操作符来控制;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "test 1 =======" << endl;
double f = 3.1415926535;
cout << f << endl; // 3.14159
cout << setiosflags(ios::fixed); //只有在这项设置后,setprecision才是设置小数的位数。
cout << setprecision(0) << f << endl; //输出0位小数,3
cout << setprecision(1) << f << endl; //输出1位小数,3.1
cout << setprecision(2) << f << endl; //输出2位小数,3.14
cout << setprecision(3) << f << endl; //输出3位小数,3.142
cout << setprecision(4) << f << endl; //输出4位小数,3.1416
cout << "test 2 =======" << endl;
//cout.setf跟setiosflags一样,cout.precision跟setprecision一样
float a = 0.546732333;
float b = 3.563768245;
cout << a << endl;
cout << b << endl;
cout.setf(ios::fixed);
cout.precision(3);
cout << a << endl;
cout << b << endl;
cout.precision(1);
cout << a << endl;
cout << b << endl;
return 0;
}
如果不加cout << setiosflags(ios::fixed);
貌似输出的是有效数字?(好像也不是,存疑)
只有加上才能精确地控制小数点后位数。
原文:https://www.cnblogs.com/Adalight/p/14746557.html