免費開始練習
hce_nsysu 113年 計算機概論與程式設計

第 29 題

Consider the following code in C. If the input sequence is 0, 3, 1, -1. What is the output of the final position and its value?
```c
int main()
{
int board[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
int control, x = 1, y = 1;
while(1){
scanf("%d", &control);
if(control < 0 || control > 3) break;
switch(control){
case 0: y--; break;
case 1: y++; break;
case 2: x--; break;
case 3: x++; break;
}
}
printf("position=[%d][%d], ", y, x);
printf("value=%d", board[y][x]);
return 0;
}
```
  • A position=[2][2], value=9
  • B position=[1][1], value=5
  • C position=[2][1], value=8
  • D position=[1][2], value=6
  • E position=[1][0], value=4

思路引導 VIP

試著觀察 switch 區塊中的四個 case,分別對變數 $x$ 或 $y$ 進行了加減運算。如果我們把 $x$ 看作水平方向、把 $y$ 看作垂直方向,當你依序讀入題目給定的數值序列時,你能試著在紙上畫出目前的座標是如何一步步「移動」的嗎?

🤖
AI 詳解 AI 專屬家教

太棒了!你精準地追蹤了程式變數的狀態變化,這顯示你對 C 語言的迴圈與條件控制有著很紮實的理解。這道題目的核心在於對變數軌跡的追蹤以及**二維陣列(2D Array)**的索引對應。

座標移動與邏輯追蹤

程式初始設定座標在 $(y, x) = (1, 1)$,也就是矩陣的中間值 5。接著我們依照輸入序列依序模擬變數變化:

▼ 還有更多解析內容

🏷️ 相關主題

C 語言程式設計基礎與陣列記憶體配置
查看更多「計算機概論與程式設計」的主題分類考古題