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가 작동하는 이유는 무엇입니까?

답변

1

당신의 질문은 당신이 완전히 ifwhile을 완전히 이해하지 못했음을 말해줍니다. 함께 사용하면 혼란스러워집니다.

if 조건이 true 인 경우에는 else이 항상 필요한 것은 아니며 false 인 경우 아무 것도 수행하지 않습니다.

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 

는 희망이

을하는 데 도움이
관련 문제