c语言中,用print可以有格式符号,例如想让a保留两位小数
float a;
print( "%.2f", a);
注意这里如果a是0.1, 那么打印出来会自动补0,也就是结果显示为0.10。
c++中没有这种格式符,所以用std中函数设定。(iomanip库)
一种写法是提前声明,一种是cout << xxx << endl中声明
#include <iostream>
#include <iomanip> using namespace std; int main()
{
float a = 0.123;
cout << a << " without setting" << endl; cout << setprecision() <<a << " without fixed" << endl; cout.setf( ios::fixed );
cout << setprecision() << a << " with fixed" << endl; cout.setf(ios::fixed);
cout.precision();
cout << a << " with fixed" << endl;
}
输出结果为
0.123 without setting
0.123 without fixed
0.12300 with fixed
0.12300 with fixed
setprecision()控制输出流,所以要写在cout << xxxxxxxxxxxxx <<endl中,
cout.precision可以提前控制输出精度,
两种方法都可以设置精度大小
fixed是设置补零,如果不想补零,可以关闭fixed设定
cout.unsetf(ios::fixed);
PS:设置精度是会四舍五入的,比如0.987,设置精度为2,则会进一位 输出0.99