关于C++的精度输出的解释。cout.precision()
网上解释cout.precision()是控制浮点数的输出精度的。这句话是没有错误的。但是程序又提示cout.precision()是控制输出结果的小数点位数的。这句话是不对的。我们可以做简答的实验验证
错误的解释程序如下:
#include<iostream>
using namespace std;
int main()
{
double a =3.1415926;
cout.precision(1);//输出小数点后一位
cout<<"the first : "<<a<<endl;
cout.precision(2);//输出小数点后一位
cout<<"the second : "<<a<<endl;
cout.precision(3);//输出小数点后一位
cout<<"the third :"<<a<<endl;
return 0;
}
the first : 3
the second : 3.1
the third : 3.14
我们再试一下命令a=a =0.001415926;
输出结果如下:
the first : 0.001
the second : 0.0014
the third : 0.00142
由以上的验证我们可以知道“cout.precision()是控制输出结果的小数点位数”的表述是错误的。cout.precision()实际是控制输出结果的有效数字的。
在此更正。
如有错误,欢迎改正!!