輸入 m (2<m<10),輸出 m×m 陣列,第 i 列、第 j 欄(0-base)值為 (i+1)*(j+1)。即乘法表矩陣。
#include <stdio.h>
int main() {
int m;
printf("請輸入 m (2 < m < 10): ");
scanf("%d", &m);
if (m <= 2 || m >= 10) {
printf("輸入超出範圍。\n");
return 1;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
printf("%-4d", (i+1)*(j+1)); // %-4d 左對齊寬度4
}
printf("\n");
}
return 0;
}
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
原始回答的程式碼邏輯錯誤(`m=1` 初始化、`m+=j+1` 累加),導致輸出不符合規律。上述雙重迴圈直觀對應數學定義。
int find_max(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
return max;
}
double avg_2d(int rows, int cols, int arr[rows][cols]) {
long long sum = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
sum += arr[i][j];
return (double)sum / (rows * cols);
}
回傳找到的位置(列、欄)或 -1。雙重迴圈遍歷比對。
int a[10] = {1,3,4,5,6};
int *p = a; // 等價 &a[0]
for (int i = 0; i < 5; i++) {
printf("%d ", *(p+i)); // 或 p[i]
}
struct Student {
int num;
char name[20];
float score[3];
};
void print_students(struct Student s[], int n) {
for (int i = 0; i < n; i++) {
printf("%d %s %.1f %.1f %.1f\n", s[i].num, s[i].name, s[i].score[0], s[i].score[1], s[i].score[2]);
}
}
FILE *fp = fopen("test.txt", "w");
char ch;
while ((ch = getchar()) != '!') fputc(ch, fp);
fclose(fp);
FILE *fp = fopen("test.txt", "w");
char ch;
while ((ch = getchar()) != '!') fputc(toupper(ch), fp);
fclose(fp);
這八題涵蓋**陣列操作、函數模組化、指標、結構體、檔案 I/O、字元處理**等核心主題。建議逐題獨立完成、編譯測試、對照規格驗證,再整合成完整專案。