在C語言中,要使用scanf
函數輸入多維數組,可以通過嵌套循環逐個元素地讀取數據
#include<stdio.h>
int main() {
int rows, cols;
// 輸入數組的行數和列數
printf("請輸入數組的行數: ");
scanf("%d", &rows);
printf("請輸入數組的列數: ");
scanf("%d", &cols);
// 分配內存空間
int array[rows][cols];
// 輸入數組元素
printf("請輸入數組元素(每個元素后按回車鍵):\n");
for (int i = 0; i< rows; i++) {
for (int j = 0; j< cols; j++) {
scanf("%d", &array[i][j]);
}
}
// 打印數組
printf("輸入的數組為:\n");
for (int i = 0; i< rows; i++) {
for (int j = 0; j< cols; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}
這個示例程序首先提示用戶輸入數組的行數和列數,然后根據這些值創建一個二維數組。接下來,程序使用嵌套循環逐個讀取數組元素,并將它們存儲在數組中。最后,程序打印出輸入的數組。