在C++,使用cout对浮点数据控制输出时,可以有几种写法。
1.对浮点数据的精度控制,使用cout输出时,它默认输出6位有效数字。
2.可以修改浮点数据的输出精度,使用cout.precision(4);,即为控制输出精度为4位的有效数字。
3.使用定点法,cout.flags(cout.fixed);可以控制输出小数点后面的位数(上面为4),即小数点后面为4位数字。
4.不再使用定点法时,用cout.unsetf(cout.fixed);取消,输出的仍然是4位有效数字。
如下↓
#include<iostream>
#include<Windows.h>
using namespace std;
int main(void) {
double value = 12.3456789;
//默认输出6位有效数字
cout << value << endl;//12.3457
//修改cout的输出精度为4(有效数字)
cout.precision(4);
cout << value << endl;
//如果想要这个精度,用来表示小数点后面的位数
//定点法:精度,用来表示小数点后面的位数(上面设置为4)
cout.flags(cout.fixed);
cout << value << endl;
cout << 12.54235 << endl;
//取消定点法
cout.unsetf(cout.fixed);
cout << 12.54235 << endl;
system("pause");
return 0;
}