我仍然是一個初學者,我只是想知道我的回圈是否還有其他方法可以讓我為了學習而撰寫它。這是我的回圈:
int count = 0;
int index = 0;
while(index >= 0 && index < arr.length && count < 100){
index = arr[index];
count ;
}
uj5u.com熱心網友回復:
您可以for loop
用于該任務,因此您可以撰寫:
for (int count = 0, index = 0; index >= 0 && index < arr.length && count < 100 ;count )
{
index = arr[index];
}
但請注意,在您的 for 回圈中,您沒有更新 的值index
,我的意思index
是即使在您的原始代碼中也始終為 0
uj5u.com熱心網友回復:
在這種情況下,一個很好的選擇是 for 回圈。正如您在對回圈使用多個條件進行編碼時會注意到的那樣,最好使用 for 回圈,因為它看起來更整潔,并且 for 回圈已經需要三個非常適合您的情況的條件。
while ( condition && condition && condition)
vs
for ( condition ; condition ; condition)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511137.html
標籤:循环
上一篇:你能告訴我這個回圈有什么問題嗎?
下一篇:計算滿足變化條件的行數