題目 1:輸入 5 整數,輸出奇數,無則印 None
#include <stdio.h>
int main() {
int a[5], cnt = 0;
printf("請輸入 5 個整數:");
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
if (a[i] % 2 != 0) {
printf("%-4d", a[i]);
cnt++;
}
}
if (cnt == 0) printf("\nNone\n");
else putchar('\n');
return 0;
}
題目 2:輸入 m, n,每行 7 個數輸出區間所有整數
#include <stdio.h>
int main() {
int m, n;
scanf("%d %d", &m, &n);
int start = (m < n) ? m : n;
int end = (m > n) ? m : n;
int per_line = 0;
for (int i = start; i <= end; i++) {
printf("%-4d", i);
if (++per_line % 7 == 0) putchar('\n');
}
if (per_line % 7 != 0) putchar('\n');
return 0;
}
題目 3:輸入 n,用 double 計算 n! (n ≤ 170 避免溢出)
#include <stdio.h>
int main() {
int n;
printf("請輸入非負整數:");
scanf("%d", &n);
double fact = 1.0;
for (int i = 2; i <= n; i++) fact *= i;
printf("%d! = %.0f\n", n, fact); // %.0f 不科學計數法顯示整數部份
return 0;
}
題目 4:算術表達式實現
| 需求 | 表達式 | 說明 |
| 實數 x 四捨五入為整數 | (int)(x + 0.5) (x ≥ 0) | 負數需 (int)(x - 0.5) 或用 round() (C99 math.h) |
| 實數 y 保留小數點後 2 位 (第三位四捨五入) | (int)(y * 100 + 0.5) / 100.0 | 或 printf("%.2f", y) 僅顯示 |
| 三位正整數 z 拆解百/十/個位 | z/100, (z/10)%10, z%10 | 整除與取模組合 |
綜合測試主程式
int main() {
// 測試四捨五入
double x = 3.14, y = 2.71828;
printf("round(%.2f)=%d\n", x, (int)(x+0.5));
printf("%.2f 保留兩位: %.2f\n", y, (int)(y*100+0.5)/100.0);
// 拆解位數
int z = 387;
printf("%d -> 百:%d 十:%d 個:%d\n", z, z/100, (z/10)%10, z%10);
return 0;
}
核心知識點總結
scanf 格式字串 "%d %d" 自動跳過空白 (含換行)。
printf 寬度 %-4d 左對齊、%4d 右對齊,利於對齊輸出。
double 階乘可到 170!,超過用 long double 或大整數庫。
- 四捨五入本質:
floor(x + 0.5) (正數),ceil(x - 0.5) (負數),標準庫 round() 已處理完備。