2016-02-28 23 views
1

我正在設計一個用作遊戲的數字猜測算法。爲什麼算法在第一個條件之後結束?

任何人都可以提出爲什麼算法在第一個條件後結束?

#include <iostream> 

using namespace std; 

int main() 
{ 

int num = 5; 
int guess; 

cout << "Guess a number \n"; 
cin >> guess; 


if (guess==num) 
{ 
    cout << "You guessed the correct number \n"; 
} 
else if (guess < num) 
{ 
    cout << "Your guess is lower than the number \n"; 
    cout << "Guess again \n"; 
    cin >> guess; 
} 
else 
{ 
    cout << "Your guess is higher than the number \n"; 
    cout << "Guess again \n"; 
    cin >> guess; 
} 


return 0; 

}

+2

你需要一個循環 – user3528438

+0

@ user3528438不知道怎麼做,但我相信我會找到你的時間在網上的東西感謝:d –

回答

0

,如果你想,該算法將重複你需要一些類型的循環。

例如

#include <iostream> 

using namespace std; 

int main() 
{ 
    int num = 5; 
    int guess; 

    cout << "Guess a number \n"; 

    do 
    { 
     cin >> guess; 

     if (guess == num) 
     { 
      cout << "You guessed the correct number \n"; 
     } 
     else if (guess < num) 
     { 
      cout << "Your guess is lower than the number \n"; 
      cout << "Guess again \n"; 
     } 
     else 
     { 
      cout << "Your guess is higher than the number \n"; 
      cout << "Guess again \n"; 
     } 

    } while (guess != num); 

    return 0; 
} 
+0

@AgelosNuho沒有在所有:) –

0

如果您想再次猜我推薦一個循環。否則,您的代碼按預期工作。

while(number != guess) 
     { 
      if(number * 2 < guess){ 
       cout << "Way to high. Try again." << endl; 
       cin >> guess; 
      } 

      if(number/2 > guess) 
      { 
       cout << "Tip : My number is NOT low. Try again." << endl; 
       cin >> guess; 
      } 

      if(number < guess) 
      { 
       cout << "To high try something lower. Feed me a number." << endl; 
       cin >> guess; 
      } 
      if(number > guess) 
       cout << "To low, try again." << endl; 
       cin >> guess; 
     } 
相關問題