来源:https://www.bilibili.com/video/BV12x411D7xr?p=127
在我的vs2019中执行以下代码:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a = sin(1)*1000;
double b = 1.0;
cout << a<<endl;
cout << fixed << a << endl;
cout << b << endl;
return 0;
}
输出:
可见cout对double型的数据默认输出6位有效数字,当使用fixed后会把之后的输入流固定输出小数点后六位的数字。
同时fix的还会把科学计数法的输出格式转化为非科学计数法的输出
如果想要自定义输出精度的话可以使用setprecition,使用时要#include
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double a = sin(1)*1000;
double b = 1.0;
double c = a * 1000000;
cout << a << endl;
cout << setprecision(10) << a << endl;
cout << c << endl;
return 0;
}
发现第二行并没有输出小数点后十位,同时第三行小数点后甚至只有一位,因为setprecision(10)输出的是十位有效数字
更改一下,加上fixed就可以了,如下:
double a = sin(1)*1000;
double b = 1.0;
double c = a * 1000000;
cout << a << endl;
cout << setprecision(10) << a << endl;
cout <<fixed<< setprecision(10) << a << endl;
cout << c << endl;
需要注意的是如果要超出double类型精度范围的小数位数,超出的部分会不准确
double a = 10000 / 3.0;
cout << fixed << setprecision(20) << a << endl;
输出:
另外使用setw()可以控制输出的数字,字符的宽度:
right 右对齐,left 左对齐
int a = 1, b = 1000000;
cout << right << setw(3) << a << endl;
cout << left << setw(3) << a << endl;
cout << setw(3) << b << endl;
setfill()可以填充字符的宽度
int a = 1, b = 1000000;
cout << setfill('*');
cout << right << setw(3) << a << endl;
cout << left << setw(3) << a << endl;
cout << setw(3) << b << endl;