2016-07-31 161 views
-1

我在C++中提出了一個程序,要求輸入任何整數。該程序只有2次迭代後崩潰。代碼如下:if語句正在運行時只有一條語句

#include<iostream> 

int main() 
{ 
    int user_choice; 
    std::cout <<"Please enter any number other than five: "; 
    std::cin >> user_choice; 

    while(user_choice != 5) 
    { 
     std::cout <<"Please enter any number other than five: "; 
     std::cin >> user_choice; 
     if(user_choice == 5) 
      std::cout << "Program Crash"; 
      break; 
    } 
    std::cout << "I told you not to enter 5!"; 
    return 0; 
} 

然後我試着這樣做:

if(user_choice == 5) 
    std::cout << "Program Crash"; 
    //std::cout << "Shutting Down"; 

哪些工作。爲什麼註釋掉第二行,導致程序運行正常?

+2

'if(condition){statement1;語句2; }' – LogicStuff

+0

@LogicStuff能否請你解釋一下你的評論 –

+1

還有更多的代碼,比如,你爲什麼要比較'user_choice'和'5'文字,你應該做'user_choice == right_answer'?爲什麼你覺得有必要將'right_answer'分配給'user_choice'如果它們已經相等了?你還將'5'硬編碼到輸出消息中...... – LogicStuff

回答

2

此代碼:

if (counter == 10) 
    std::cout << "Wow you still have not entered 5. You win!"; 
    user_choice = right_answer; 

Is eq uivalent到:

if (counter == 10) 
{ 
    std::cout << "Wow you still have not entered 5. You win!"; 
} 
user_choice = right_answer; 

你的問題變得明顯,user_choice = right_answer不執行,只有當counter == 10。因此,將其移動到if() { ... }塊內:

if (counter == 10) 
{ 
    std::cout << "Wow you still have not entered 5. You win!"; 
    user_choice = right_answer; 
} 
+2

@ Mr.Python絕對不會,如果你還沒有,可以拿一本C++書。你不能跳入C++並應用其他語言的結構......你會遇到類似的問題。 – user2296177

+0

@ Mr.Python我建議在那裏查找「範圍」。 – user2296177

+1

是的,實際上學習語言讓你更擅長這一點令人驚訝。 –

1

C++不尊重縮進;所以,當你寫:

if (counter == 10) 
    std::cout << "Wow you still have not entered 5. You win!"; 
    user_choice = right_answer; 

編譯器看到:

if (counter == 10) 
    std::cout << "Wow you still have not entered 5. You win!"; 
user_choice = right_answer; 

爲了把兩個語句下if,你需要括號:

if (counter == 10) { 
    std::cout << "Wow you still have not entered 5. You win!"; 
    user_choice = right_answer; 
}