阿摩線上測驗 登入

申論題資訊

試卷:99年 - 99 高等考試_三級_資訊處理:程式語言#27552
科目:程式語言
年份:99年
排序:0

題組內容

五、

申論題內容

⑵若語言本身不提供捷徑計算,則下列程式片段會出現什麼錯誤訊息?(10 分) 
    index : = 1; 
    while (index <= listlen )and (list[index]<> key)do index : = index+1; (假設 list [1..listlen]為被查詢之陣列,而 key 為要查詢之值)

詳解 (共 1 筆)

詳解 提供者:hchungw
index := 1;
while (index <= listlen) and (list[index] <> key) do
    index := index + 1;
問題分析
在上述程式碼中,while 迴圈的條件是 (index <= listlen) and (list[index] <> key)。這意味著在每次迴圈迭代中,程式會先檢查 index <= listlen,然後再檢查 list[index] <> key。
錯誤情境
如果程式語言不提供捷徑計算(short-circuit evaluation),那麼兩個條件 (index <= listlen) 和 (list[index] <> key) 都會被評估,即使前一個條件已經可以確定整個條件的結果。例如:
當 index > listlen 時,條件 (index <= listlen) 為 false。
此時,如果語言不提供捷徑計算,會繼續評估 list[index] <> key。
因為 index 已經超過 listlen,會嘗試訪問 list[index],這會導致陣列越界錯誤(array out of bounds error)。
錯誤訊息
典型的錯誤訊息可能包括:
陣列越界錯誤(Array out of bounds error)
存取違規錯誤(Access violation error)
非法記憶體存取錯誤(Segmentation fault)
這些錯誤訊息通常會在程式嘗試訪問超出陣列邊界的元素時發生,因為在不支援捷徑計算的情況下,即使 index 已經超過 listlen,仍然會評估 list[index] <> key。
解決方案
為了解決這個問題,我們可以重寫條件,使其避免直接訪問超出範圍的陣列元素。可以使用巢狀的 if 條件來模擬捷徑計算的行為:
pascal
複製程式碼
index := 1;
while (index <= listlen) do
begin
    if (list[index] = key) then
        break;
    index := index + 1;
end;
在這個改寫的版本中,先檢查 index <= listlen,如果為 false 則退出迴圈;如果為 true,才進一步檢查 list[index] = key,從而避免了陣列越界的問題。