问题来自51nod-2135题: # 价钱统计
题目要求保留一位小数,如果直接输出,如下程序
#include <bits/stdc++.h>
using namespace std;
int main (){
double a = 4, b = 3, c = 2.5, d = 6;
cout << setprecision(1) << fixed << a*1.2 << endl ;
cout << setprecision(1) << fixed << b*3.5 << endl ;
cout << setprecision(1) << fixed << c*4.5 << endl ;
cout << setprecision(1) << fixed << d*5.0 << endl ;
cout << setprecision(1) << fixed << a*1.2+b*3.5+c*4.5+d*5.0 << endl ;
return 0;
}
输出结果
4.8
10.5
11.2
30.0
56.5
上述程序中保留小数位数的setprecision改成printf("%.1lf"),结果也是一样的。
精确结果应该是
4.80
10.50
11.25
30.00
56.55
从上面的结果来看,c++中保留小数位数既不是按“四舍五入”,也不是按“四舍六入五留双”。
“四舍五入”大家都熟悉,那么什么是“四舍六入五留双”,我们又为什么要用“四舍六入五留双”呢,详情请看# 百科
最后,我们怎么实现指定小数位数的“四舍五入”呢,可以这么做,以保留一位小数为例:先把数字扩大10位,这样原先的小数点后一位变成了个位,然后我们用round()函数四舍五入成整数,再把结果缩小10位,即为所要的结果。用代码实现即为
round(n*10)/10