假如我们遇到了这样一道题:
【题目描述】
给你一个浮点数f,输出它保留n位小数(四舍五入)后的结果。
【输入格式】
输入两个数,分别为f和n。
【输出格式】
一个数,即最终结果。
【输入样例】
3.15 1
【输出样例】
3.2
【说明】
f可以用double储存,1<=n<=5。
看过题后,LYF dalao吐槽到:
fAKe?这么简单?信不信老子用C++30s过。。。
(然而事情并没有这么简单。。。)
LYF dalao似乎在20后就写出来了:
#include <iostream>
#include <iomanip>
using namespace std;
int n;
double f;
int main()
{
cin >> f >> n;
cout << fixed << setprecision(n) << f << endl;
return 0;
}
LYF他测试了样例,结果是:
(以下是控制台内容)
3.15 1
3.1--------------------------------
Process exited after -INF seconds with return value 0
请按任意键继续. . .
(不信的同学可以到这里试一试)
LYF又是一顿吐槽:
蛤?这是啥玩意啊?用printf试试。。。
他又写了一份代码:
#include <iostream>
#include <cstdio>
using namespace std;
int n;
double f;
char com[7]="%. lf\n";
int main()
{
cin >> f >> n;
com[2] = n + '0';
printf(com, f);
return 0;
}
结果。。。毫无变化
(以下是控制台内容)
3.15 1
3.1--------------------------------
Process exited after -INF seconds with return value 0
请按任意键继续. . .
(同样,不信的话可以到这里试试)
LYF dalao陷入了崩溃状态。。。
那么,我们回首这场悲剧,来探究问题的根源。
蒟蒻我写了一份代码,来研究C++/C(cout/printf)在对浮点数进行四舍五入Output时情况:
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
char com[7]="%. lf\n";
int main()
{
cout << "It's cout:" << endl;
out << fixed << setprecision(1) << "base: " << 3.15 << endl;
cout << fixed << setprecision(1) << "test1:" << 3.150 << endl;
cout << fixed << setprecision(1) << "test2:" << 3.153 << endl;
cout << fixed << setprecision(1) << "test3:" << 3.155 << endl;
cout << fixed << setprecision(1) << "test4:" << 3.159 << endl;
cout << fixed << setprecision(2) << "test5:" << 3.155 << endl;
cout << fixed << setprecision(2) << "test6:" << 3.15533 << endl;
cout<<endl;
printf("It's printf\n");
printf("base: ");
com[2] = 1 + '0';
printf(com, 3.15);
printf("test1:");
com[2] = 1 + '0';
printf(com, 3.150);
printf("test1:");
com[2] = 1 + '0';
printf(com, 3.153);
printf("test1:");
com[2] = 1 + '0';
printf(com, 3.155);
printf("test1:");
com[2] = 1 + '0';
printf(com, 3.159);
printf("test1:");
com[2] = 2 + '0';
printf(com, 3.155);
printf("test1:");
com[2] = 2 + '0';
printf(com, 3.15533);
return 0;
}
(老规矩,发放测试入口)
运行结果如下:
(以下是控制台内容)
It's cout:
base: 3.1
test1:3.1
test2:3.2
test3:3.2
test4:3.2
test5:3.15
test6:3.16It's printf
base: 3.1
test1:3.1
test1:3.2
test1:3.2
test1:3.2
test1:3.15
test1:3.16--------------------------------
Process exited after 0.INF seconds with return value 0
请按任意键继续. . .
当我们分析上面的运行结果后,可总结如下规律:
- C++/C(cout/printf)在对浮点数进行四舍五入Output时所发生的现象一样,即进行的操作相同。
- 若要四舍五入保留n位小数,当小数后第n+1位数x满足0<=x<=4或6<=x<=9时,C++/C可正确四舍五入,输出正确答案。
- 当x=5时,若第n+1位后还有数字(如测试中的3.153),可正确四舍五入;但是如果没有(如测试中的3.15),可能会输出错误答案(至于为什么是“可能”,因为我后来发现这种情况下不一定会错)。
由此,我们可以发现,cout/printf在保留小数的时候,有非常大的问题(后来我了解到C++/C的机制是四舍六入五成双,不是四舍五入),所以我们最好不要直接用它们四舍五入了。
蛤?你问我该用啥?
当然是这个啦:
inline double FourCutFiveKeep(double num,int t)
{
int pow10t=1;
while(t!=0)
{
pow10t *= 10;
t--;
}
return (int)(num * (double)pow10t + 0.5) / (double)pow10t;
}
(于是,我们有了一开始那道题的正解)
异 同步发表于:洛谷