| 需求 | 方法 | 程式碼 | 影響範圍 |
|---|---|---|---|
| 僅**顯示**保留 2 位 | 格式化輸出 | printf("%.2f", val); | 不改變變數值,後續計算仍用完整精度 |
| **數值**四捨五入到 0.01 | 數值修改 | val = round(val * 100.0) / 100.0; | 實際改變儲存值,後續計算使用近似值 |
// 缺陷示範
float n = 1.005f;
n = (int)(n * 100 + 0.5) / 100.0f;
// n * 100 = 100.5 (二進位無法精確表示,可能為 100.499999)
// +0.5 = 100.999999
// (int) = 100
// 結果 1.00,正確應為 1.01
二進位浮點誤差導致邊界條件失效。
#include
double round2(double x) {
return round(x * 100.0) / 100.0;
}
// 負數自動正確處理:round(-1.234*100)/100 = -1.23
// 方案一:整數分 (最推薦)
int price_cents = 1999; // 19.99 元
// 運算全用整數,顯示時分離元/分
printf("%d.%02d", price_cents/100, price_cents%100);
// 方案二:定點數結構體
typedef struct { int integer; int fraction; } Money; // fraction 0~99
// 方案三:C23 _Decimal64 / 第三方 decNumber 庫
printf("%.2f")。round(x*100)/100。(int)(x*100+0.5)/100.0,邊界誤差極難除錯。