1.cout语句运算结果保留n位小数
- 添加头文件 #include <iomanip>
- 将输出语句 cout << num3; 改为 cout << fixed<< setprecision(3) << num3 << endl; 这样是在保留小数点后 3 位小数的,它自带四舍五入;
- 如果输出语句仅仅是 cout << setprecision(3) << num1 << endl; 这样只是在保留三位有效数字,即,从结果第一个不为 0 的数开始数起,保留相应的几位数;
- 需要注意的是,此种设置输出格式,只要设置一次,以后的输出格式就都被覆盖掉了,所以程序里只用设置一次以后就可以直接输出了。
下面的测试程序中输出1与输出3代码一致,但是结果是不一样的。
测试程序:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
float num1 = 0.00123456789;
float num2 = -0.123456789;
float num3 = 1234.123456789;
// 保留有效位数,从第一位不是 0 的数字开始,共n位 ,最后一位四舍五入
cout << "保留有效位数,对正数小数的输出1:" << endl;
cout << setprecision(3) << num3 << endl;
cout << setprecision(4) << num3 << endl;
cout << setprecision(5) << num3 << endl;
cout << endl;
cout << "保留末尾小数,对正数小数的输出2:" << endl;
cout << fixed<< setprecision(3) << num3 << endl;
cout << fixed<< setprecision(4) << num3 << endl;
cout << fixed<< setprecision(5) << num3 << endl;
cout << endl;
cout << "保留有效位数,对正数小数的输出3:" << endl;
cout << setprecision(3) << num3 << endl;
cout << setprecision(4) << num3 << endl;
cout << setprecision(5) << num3 << endl;
cout << endl;
cout << "保留末位小数,对负数小数的输出4:" << endl;
cout << setprecision(3) << num2 << endl;
cout << setprecision(4) << num2 << endl;
cout << setprecision(6) << num2 << endl;
cout << num2 << endl;
cout << num3 << endl;
return 0;
}
2.printf 语句运算结果保留n位小数
- 添加头文件 #include <cstdio>
- 将输出语句 printf("%.4f\n", num1); 小数点后面的数字代表保留的小数位数,它也自动四舍五入。
程序测试:
#include <iostream>
#include <cstdio>
int main(){
float num1 = 0.0123456789;
float num2 = -0.123456789;
float num3 = 1234.123456789;
printf("输出正数小数的保留n位:\n"); // 带四舍五入
printf("%.4f\n", num1);
printf("%.5f\n", num1);
printf("%.6f\n", num1);
printf("输出正数小数的保留n位:\n"); // 带四舍五入
printf("%.4f\n", num3);
printf("%.5f\n", num3);
printf("%.6f\n", num3);
printf("输出负数小数的保留n位:\n"); // 带四舍五入
printf("%.4f\n", num2);
printf("%.5f\n", num2);
printf("%.6f\n", num2);
return 0;
}