實現保留 n 位小數的四捨五入。核心原理:放大 → 加 0.5 截斷 → 縮小。兩種代碼實現對比。
#include <stdio.h>
long pow10(int n) {
long r = 1;
while (n-- > 0) r *= 10;
return r;
}
int main() {
float h = 11.5555;
int prec = 3; // 保留 3 位小數
long t = (long)((h * pow10(prec + 1) + 5) / 10.0);
float result = (float)t / pow10(prec);
printf("%.3f\n", result); // 11.556
return 0;
}
優點:負數正確。缺點:隱式轉換風險,pow10 遞歸棧深。
double pow10_d(double n) {
if (--n > 0) return 10 * pow10_d(n);
return 1;
}
int main() {
double x = 11.55556666;
int prec = 3;
double factor = pow10_d(prec);
double y = 0.01 * 1.0 / factor * (int)(100.0 * factor * (x + 0.005 / factor));
printf("%.3f\n", y);
return 0;
}
缺點:負數不正確,公式複雜易錯。
#include <math.h>
// 保留 n 位小數四捨五入
double round_n(double x, int n) {
double factor = pow(10, n);
return round(x * factor) / factor; // C99 round() 正確處理負數
}
// 輸出格式化 (不改變值)
printf("%.3f", x); // 自動四捨五入顯示
0.1 + 0.2 = 0.30000000000000004float 仅 6-7 位有效數字,double 15-16 位printf("%.nf")round(x * pow(10,n)) / pow(10,n)decimal 庫