錯誤程式碼
double a, b, c, s;
scanf("%f%f%f", &a, &b, &c); // 錯誤:%f 對應 float
printf("s=%f", s); // 錯誤:%f 對應 float
根本原因
double 佔 8 bytes,float 佔 4 bytes。
scanf("%f") 只寫入 4 bytes,高位殘留垃圾值 → 數值錯誤。
printf("%f") 讀取 4 bytes 解釋為 float,同樣導致輸出錯誤。
正確格式字串對照表
| 型別 | scanf | printf | 備註 |
| float | %f | %f | 預設提升為 double,printf 兩者通用 |
| double | %lf | %f 或 %lf | scanf 必須 %lf;printf %f/%lf 均可 (C99) |
| long double | %Lf | %Lf | |
修正後程式碼
#include <stdio.h>
#include <math.h>
double sabc(double a, double b, double c) {
double p = (a + b + c) / 2.0;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
int main() {
double a, b, c, s;
printf("請輸入三角形三邊長:");
scanf("%lf%lf%lf", &a, &b, &c); // 關鍵修正
s = sabc(a, b, c);
printf("面積 s = %.2f\n", s); // printf 可用 %f
return 0;
}
延伸提醒
scanf 系列必須精確匹配型別大小,否則未定義行為。
printf 因預設引數提升,float 自動轉 double,故 %f 兼容兩者;但 scanf 無提升機制,嚴禁混用。
- 良習:
scanf 全用 %lf 讀 double,printf 統一 %f 輸出浮點數。
牢記 scanf 讀 double 用 %lf,printf 輸出浮點數用 %f,徹底根除型別不匹配導致的數值謎之錯誤。
- 上一篇文章: C 語言二進制輸出迴圈多一個分號導致無輸出:scanf_s 回傳值判斷陷阱
- 下一篇文章: Delphi ShowMessage 被最小化視窗縮圖遮蓋:手動建立主視窗釋放登入視窗解決 Z-Order 問題
Copyright ©
程式碼之家 All Rights Reserved