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

第 14 題

You are given a Python function that is supposed to calculate the sum of all integers from 1 to n using recursion. However, there is a mistake in the code. Identify the mistake and provide the corrected version of the code.
```python
def sum_to_n(n):
if n == 1: # base case
return 1
else:
return n + sum_to_n(n)
```
  • A Change sum_to_n(n) to sum_to_n(n-1) in the recursive call
  • B Change return 1 to return 0 in the base case
  • C Change n + sum_to_n(n) to n * sum_to_n(n) in the recursive call
  • D Change the base case from n == 1 to n == 0
  • E Change return 1 to return n in the base case

思路引導 VIP

如果你現在站在 10 樓,目標是走到 1 樓,但你設定的規則是「每走一步,就重新詢問一次自己如何在 10 樓往下走」,你覺得你最後能抵達 1 樓嗎?為了讓程式最終能碰到「n == 1」這個終止條件,每一次呼叫函式時,傳進去的參數應該要比上一次多、少,還是維持不變呢?

🤖
AI 詳解 AI 專屬家教

太棒了!你能一眼看出這段程式碼的邏輯漏洞,代表你對「遞迴」的執行過程有相當清晰的理解。這道題目的核心在於遞迴的收斂性。在原始程式碼中,雖然我們定義了 $n=1$ 的基底情形(Base Case),但在遞迴步驟卻使用了 sum_to_n(n)。這會導致程式不斷地呼叫自己,且傳入的參數始終不變,進而陷入無限循環,最終導致堆疊溢位(Stack Overflow)。

遞迴邏輯的關鍵與修正

要讓遞迴正確運作,每一次的函式呼叫都必須讓問題規模「縮小」,朝向基底情形靠近。因此,我們必須將參數修改為 $n-1$,讓數值從 $n$ 逐步遞減到 $1$,這正是選項 (A) 的修正方案。這題的難度雖然屬於基礎,但它極具鑑別度,能有效測驗出開發者是否真正理解遞迴在執行時的動態變化,而不僅僅是背誦語法公式。

🏷️ 相關主題

計算機組織結構與資料儲存原理
查看更多「計算機概論與程式設計」的主題分類考古題