2015-02-07 80 views
-3

我在大學學習,我們開始用C++編程。我有一些關於Java的基本概念(變量,循環和更簡單的事情),我試圖用Microsoft Visual Studio自己練習,但是我遇到了問題,這是我的代碼,是一個試圖猜測你的數字的程序正在考慮。C++只有2個循環迭代

void main(){ 
srand(time(NULL)); 
int number=1+rand()%100; 
int highLow; 
bool a; 
a = true; 
cout << "Think a number between 1 and 100 and I will guess it" << endl; 
system("PAUSE"); 
cout << "\nIs it "; 
cout << number; 
cout << "?" << endl; 
cout << "If the number is lower press 1, higher 2 and correct 3" << endl; 
cin >> highLow; 
while (a) 
{ 
    if (highLow == 1) 
    { 
     number = 1 + rand() % number; 
     cout << "\nIs it "; 
     cout << number; 
     cout << "?" << endl; 
     cin >> highLow; 
    } 
    else if (highLow == 2) 
    { 
     number = rand() % (100 - number+1)+number; 
     cout << "\nIs it "; 
     cout << number; 
     cout << "?" << endl; 
     cin >> highLow; 
    } 
    else if (highLow == 3) 
     cout << "I win this time" << endl; 
     a = false;} 
} 

的問題是,應該要求用戶多次需要猜測的數目,但它只做2次,然後停止。你能幫我嗎?

+2

_「你能幫我嗎?」_我認爲你的調試器可以在這裏得到更多的幫助。學習使用你的工具。 – 2015-02-07 17:56:51

+0

'void main()' - 請不要。 'main()'返回'int'。 – 2015-02-07 17:57:36

+0

請參閱https://www.youtube.com/watch?v=C0vDKXIq_9A並稍後感謝我。 – sashoalm 2015-02-07 17:59:39

回答

1

如果只有你已經縮進你的代碼正確...

最後a = false;語句執行不管是什麼,因爲這是最後else if語句的範圍之外。基本上,這個:

else if (highLow == 3) 
    cout << "I win this time" << endl; 
    a = false; 

意味着:

else if (highLow == 3) { 
    cout << "I win this time" << endl; 
} 

a = false; 

你需要酌情增加一些大括號內。