2017-02-21 1 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でelseコンポーネントを使用しないと、なぜ動作しますか?

答えて

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 

が、これは

を役に立てば幸い
関連する問題