分析 无论用printf还是用setprecision,都无法达到四舍五入的结果。
#include <iostream>#include <cstdio>#include <iomanip>using namespace std;int main(){ printf("%.1f\n", 1.15); printf("%.1f\n", 1.25); printf("%.1f\n", 1.35); printf("%.1f\n", 1.45); printf("%.1f\n\n", 1.55); cout << fixed << setprecision(1) << 1.15 << endl; cout << fixed << setprecision(1) << 1.25 << endl; cout << fixed << setprecision(1) << 1.35 << endl; cout << fixed << setprecision(1) << 1.45 << endl; cout << fixed << setprecision(1) << 1.55 << endl; return 0;}
运行结果
1.11.21.41.41.61.11.21.41.41.6
从结果可以看出,浮点数保留小数位没有什么规律,既不是“四舍五入”,也不是“四舍六入五成双”。这与浮点数的不精确存储有关系。
(1)下面的代码,用Codeblocks运行的结果是1.1,用DevC++运行的结果是1.2
#include <cstdio>int main(){ float a = 1.15; a = int(a * 10 + 0.5)/10.0; printf("%.1f\n", a); return 0;}
(2)把上面的代码中的float改成double后,在Codeblocks中运行的结果仍然是1.1,在DevC++中运行的结果仍然是1.2
#include <cstdio>int main(){ double a = 1.15; a = int(a * 10 + 0.5)/10.0; printf("%.1f\n", a); return 0;}
(3)下面的代码,用Codeblocks运行的结果是1.1,用DevC++运行的结果是1.2
#include <cstdio>#include <cmath>int main(){ float a = 1.15; a = floor(a * 10 + 0.5)/10; // floor函数的返回类型为float printf("%.1f\n", a); return 0;}
(4)把上面的代码中的float改成double后,在Codeblocks中和DevC++中运行的结果都是1.2
#include <cstdio>#include <cmath>int main(){ double a = 1.15; a = floor(a * 10 + 0.5)/10; // floor函数的返回类型为double printf("%.1f\n", a); return 0;}
从这四个函数的运行结果可以看出,对于相同的取整或floor函数,不同的编程工具会出现不同的运行结果。因为考试时,指定的编程工具是DevC++,所以上面四种写法都是可以的。若是平时练习,则可以使用上面的第四种写法,即使用double和floor()结合。
(5)本题的实现代码为
#include <cstdio>#include <cmath>int main(){ double a, b, c, d, total; scanf("%lf%lf%lf%lf", &a, &b, &c, &d); a *= 1.2; b *= 3.5; c *= 4.5; d *= 5; a = floor(a * 10 + 0.5) / 10; b = floor(b * 10 + 0.5) / 10; c = floor(c * 10 + 0.5) / 10; d = floor(d * 10 + 0.5) / 10; total = a + b + c + d; printf("%.1f\n%.1f\n%.1f\n%.1f\n%.1f\n", a, b, c, d, total); return 0;}
可以使用round函数实现四舍五入
#include <cstdio>#include <cmath>int main(){ double a, b, c, d, total; scanf("%lf%lf%lf%lf", &a, &b, &c, &d); a *= 1.2; b *= 3.5; c *= 4.5; d *= 5; // round函数返回类型与参数类型一样,即参数若为double,返回double a = round(a * 10) / 10; b = round(b * 10) / 10; c = round(c * 10) / 10; d = round(d * 10) / 10; total = a + b + c + d; printf("%.1f\n%.1f\n%.1f\n%.1f\n%.1f\n", a, b, c, d, total); return 0;}
#include <iostream>using namespace std;int main(){ char c; cin >> c; int lineCnt = c - 'A' + 1; for(int i = 0; i < lineCnt; i++) { for(int j = 0; j < i; j++) { cout << ' '; // 输出左侧的空格 } char x = c - i; for(; x >= 'A'; x--) { cout << x; } for(x = 'A'; x <= c - i - 1; x++) { cout << x; } cout << endl; } return 0;}
#include <iostream>#include <iomanip>using namespace std;int main(){ int n; cin >> n; int nume = 4; // 分子 int deno = 7; // 分母 double sum = nume * 1.0 / deno; for(int i = 2; i <= n; i++) { int tmp = nume; nume = deno; deno += tmp; sum += nume * 1.0 / deno; } cout << nume << '/' << deno << endl; cout << fixed << setprecision(2) << sum; return 0;}