本文精選四道涵蓋數學運算、單位轉換、時間處理、位元操作的經典 C 語言練習題,提供標準化、可攜式、含錯誤處理的參考解答,並深度解析每題的核心知識點與常見陷阱。
需求:輸入實數 x,輸出 sqrt(x) 保留一位小數。格式:The square root of 17.0 is 4.1
#include <stdio.h>
#include <math.h>
int main(void) {
double x;
printf("輸入一個非負實數: ");
if (scanf("%lf", &x) != 1 || x < 0) {
fprintf(stderr, "錯誤:請輸入非負實數\n");
return 1;
}
double root = sqrt(x);
printf("The square root of %.1f is %.1f\n", x, root);
return 0;
}
關鍵點:math.h 的 sqrt 接受 double,編譯需連結數學庫 gcc -lm。格式字串 %.1f 對應 double。
公式:C = 5/9 × (F - 32)
#include <stdio.h>
int main(void) {
double f;
printf("輸入華氏溫度: ");
if (scanf("%lf", &f) != 1) return 1;
double c = (f - 32.0) * 5.0 / 9.0; // 關鍵:5.0/9.0 強制浮點運算
printf("攝氏溫度: %.2f\n", c);
return 0;
}
陷阱:寫成 5/9 會整數除法得 0,必須用 5.0/9.0 或 5/9.0。
需求:輸入 time1(出發)、time2(到達),格式 HHMM(如 712 = 07:12),輸出時分差。假設 time1 ≤ time2。
#include <stdio.h>
#include <stdlib.h>
int parse_time(int t) {
if (t < 0 || t > 2359) return -1;
int hour = t / 100;
int min = t % 100;
if (hour > 23 || min > 59) return -1;
return hour * 60 + min;
}
int main(void) {
int t1, t2;
printf("輸入出發時間 到達時間 (HHMM HHMM): ");
if (scanf("%d %d", &t1, &t2) != 2) return 1;
int m1 = parse_time(t1), m2 = parse_time(t2);
if (m1 < 0 || m2 < 0) {
fprintf(stderr, "時間格式錯誤 (0000-2359)\n");
return 1;
}
int diff = m2 - m1; // 題目保證 time1 ≤ time2
printf("The train journey time is %d hrs %d mins.\n", diff / 60, diff % 60);
return 0;
}
進階:支援跨午夜(time2 < time1)可加 diff = (m2 + 1440 - m1) % 1440。
規則:
範例:1257 → (0,1,4,6) → 交換 → 4601
#include <stdio.h>
int encrypt_digit(int d) { return (d + 9) % 10; } // 等價 (d + 9) % 10
int main(void) {
int num;
printf("輸入四位數 (1000-9999): ");
if (scanf("%d", &num) != 1 || num < 1000 || num > 9999) {
fprintf(stderr, "必須為四位正整數\n");
return 1;
}
int d1 = encrypt_digit(num / 1000);
int d2 = encrypt_digit((num / 100) % 10);
int d3 = encrypt_digit((num / 10) % 10);
int d4 = encrypt_digit(num % 10);
int encrypted = d3 * 1000 + d4 * 100 + d1 * 10 + d2;
printf("The encrypted number is %04d\n", encrypted); // %04d 補零
return 0;
}
# 編譯全部 (需連結 math library)
gcc -std=c11 -Wall -Wextra -o sqrt_calc sqrt_calc.c -lm
gcc -std=c11 -Wall -Wextra -o temp_conv temp_conv.c
gcc -std=c11 -Wall -Wextra -o time_calc time_calc.c
gcc -std=c11 -Wall -Wextra -o encrypt_num encrypt_num.c
# 測試
echo 17 | ./sqrt_calc
echo 98.6 | ./temp_conv
echo 712 1411 | ./time_calc
echo 1257 | ./encrypt_num
| 題目 | 核心函式/運算 | 易錯點 | 最佳實踐 |
|---|---|---|---|
| 平方根 | sqrt(), %.1f | 忘記 -lm、負數輸入 | 輸入驗證、連結數學庫 |
| 溫度轉換 | 浮點字面常數 5.0/9.0 | 整數除法 5/9=0 | 所有常數加 .0 |
| 時間計算 | 整數除模 /100 %100 | 分鐘進位邏輯、跨日處理 | 統一轉換為總分鐘運算 |
| 數字加密 | 模運算 %10、位元組合 | 位序交換邏輯、前導零輸出 | 封裝 encrypt_digit()、用 %04d |
這四道題目橫跨 math.h、浮點精度、時間編碼、模運算四大基礎領域。掌握「輸入驗證 → 核心邏輯封裝 → 格式化輸出 → 錯誤處理」的標準化編碼流程,比單純刷題更能建立扎實的 C 語言工程直覺。建議嘗試擴展:支援任意位數加密、處理 BCE 時間、實現高精度平方根(牛頓法)。