跳轉到內容

Rexx 程式設計/Rexx 指南/條件迴圈

來自華夏公益教科書,開放的書籍,開放的世界

條件迴圈測試迴圈周圍的條件,並在條件為真時重複執行一組指令。條件迴圈的型別包括 while 迴圈、until 迴圈和 repeat 迴圈。

While 迴圈

[編輯 | 編輯原始碼]

While 迴圈是一種條件迴圈,它在條件為真時重複執行一組指令。while 語句用作 do 和 end 結構的句法元件,以生成 while 迴圈。

l = 0
do while l <= 10
  say l
  l = l + 1
end

Until 迴圈

[編輯 | 編輯原始碼]

Until 迴圈是一種條件迴圈,它在條件為真時重複執行一組指令。在 Rexx 中,until 語句與 do 和 end 結構一起使用以生成 until 迴圈。

l = 1;
do until l > 10
  say l
  l = l + 1
end

Repeat 迴圈

[編輯 | 編輯原始碼]

Repeat 迴圈是一種 [條件迴圈],它在條件為真時重複執行一組 [程式碼塊] 指令。[do] 語句與 [until] 句法元件一起使用以生成 repeat 迴圈。

attempts = 1
do until attempts==10
  say "Knock! Knock!"
  attempts = attempts + 1
end

Repeat 迴圈中的程式碼塊將始終至少執行一次

[編輯 | 編輯原始碼]

請注意,與 [while] 迴圈不同,在 repeat 迴圈中,[條件] 在 [迴圈] 中的 [程式碼塊] 之後進行評估,即使它在開頭寫著。這意味著 repeat 迴圈中的程式碼塊將始終至少執行一次。

/* This snippet asks the user their age and tries again if their answer is negative. */
/* The question will always be asked at least once. */
do until age >= 0
  say "How old are you?"
  age = LineIn()
  if age < 0 then say "Your age cannot be negative."
end

cocomponents do 和 while 在迴圈開始時進行評估

[編輯 | 編輯原始碼]

如果使用 [do] 和 [while] 元件而不是 [do] 和 [until],則迴圈將表現為 [while] 迴圈,條件在迴圈開始時進行評估。如果表示式計算結果為布林 [false] 值,則這可能會導致迴圈根本不執行。

/* This snippet lets the user enter a number to start a countdown to lift off. */
/* If the user enters a negative number, there won't be a countdown at all. */
say "Where should I start the countdown?"
number = LineIn()
do while number > 0
  say number
  number = number - 1
end
say "Lift off!"
華夏公益教科書