2017-02-21 67 views
-3

有人能解釋這個循環是如何工作的嗎?我很難理解它何時會運行if語句以及何時循環回去。這個while循環是如何工作的?

// keep buying phones while you still have money 
while (amount < bank_balance) { 
    // buy a new phone! 
    amount = amount + PHONE_PRICE; 

    // can we afford the accessory? 
    if (amount < SPENDING_THRESHOLD) { 
     amount = amount + ACCESSORY_PRICE; 
    } 
} 

此外,爲什麼它仍然工作沒有其他組件與if?

回答

1

您的問題告訴我,您還沒有完全明白ifwhile本身,並一起使用它們會讓您感到困惑。

if並不總是需要else,如果條件爲真執行,如果爲假,則什麼也不做。

if(){ //if true doA() and if false, skip it 
    doA(); 
} 


if(){//if true doA() and if false, doB() 
    doA(); 
}else{ 
    doB(); 
} 

簡單的例子

int count = 10; 

while(count != 0){ 
    count = count - 1; 

    if(count == 8){ 
     count = 0; 
    } 
} 

過程:

on while check 10 != 0; 
count is now 10 - 1 
on if check if 9 == 8 // FALSE doesnt do anything 

loop back up to while 

on while check 9 != 0; 
count is now 9 - 1 
on if check if 8 == 8 // TRUE do execute 
count is now 0 

loop back up to while 

on while check 0 != 0; // FALSE 
OUT OF WHILE AND FINISH 

希望這有助於