2017-07-12 137 views
1

所以,我必須從隨機猜測遊戲編寫一個程序。該程序需要讓玩家在1-100之間猜出一個數字。至少必須使用一個功能。它需要告訴玩家他們是否太低/高,要求他們再試一次,或者如果他們猜測,請讓他們再次玩。C++隨機數猜測遊戲錯誤

我有幾個我找不出來的錯誤。

44:錯誤: '詮釋winlose' 重新聲明爲不同種類的符號的 9:錯誤:錯誤: 'G' 爲在此範圍內聲明

的 '詮釋winlose(int)的' 44先前的聲明

代碼

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

int winlose(int); 

int main() 
{ 
    int g, n, x; 

    while (x!=0) 
    { 
     do 
     { 
      srand(time(NULL)); 
      n = 1 + rand()%100; 

      cout<<"Welcome to the guessing game. I have a number between 1-100. 
       Can you guess it?"<<endl; 
      cout<<"Please enter your guess"<<endl; 
      cin>>g; 

     winlose(g); 
     } while (n!=0); 

     cout<<"Play again? Enter 0 for no, any other number for yes."<<endl; 
     cin>>x; 
    } 
    return 0; 
} 

int winlose(g) 
{ 
    if (g<n) 
    { 
     cout<<"Your guess is too low. Try again."<<endl; 
     cin>>g; 
    } 
    else if (g>n) 
    { 
     cout<<"Your guess is too high. Try again."<<endl; 
     cin>>g; 
    } 
    else (g=n) 
    { 
     cout<<"Congrats! You win. The number was "<<n<<endl; 
     n=0; 
    } 
    return g; 
    return n; 
} 
+0

'INT winlose(G)'這不是有效的函數聲明的語法 – Borgleader

+2

'INT winlose(G)' - >'INT winlose (int g)' – HolyBlackCat

+1

[離線主題]除非你真的知道你在做什麼,否則只調用'srand' **一次**。 – NathanOliver

回答

2

你除了函數聲明犯了一些錯誤。 函數聲明必須包含每個參數的類型,所以正確的方法是:

int winlose(int g); 

不能使用在其他語句的條件:(else (g=n))。如果以前的條件(ifelse if()中的條件)都不符合,則其他語句是全面的。如果您只希望在特定情況下觸發此功能,請使用另一個else if()。您不需要在每個if聲明末尾都有一個else;以else if(){...}結尾是完全正確的。

您還需要與'=='比較,而不是'='=是賦值運算符,g=n將g的值設置爲n。如果要檢查g是否等於n,則必須使用g==n

您應該在外循環中調用srand(),否則在每次猜測之後,值都會更改。

其餘被校正,有時稍微改變爲正確的性能:

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

bool winlose(int number, int givenNumber); 

int main(){ 
    int g, n, x; 
    bool guessed; 
    do { 
     srand(time(NULL)); 
     n = 1 + rand()%100; 
     cout<<"Welcome to the guessing game. I have a number between 1-100. Can you guess it?"<<endl; 
     do { 
      cout<<"Please enter your guess"<<endl; 
      cin>>g; 
      guessed = winlose(g, n); 
     } while (!guessed); 

     cout<<"Play again? Enter 0 for no, any other number for yes."<<endl; 
     cin>>x; 
    } while (x!=0); 
    return 0; 
} 

bool winlose(int g, int n) { 
    if (g<n) { 
     cout<<"Your guess is too low. Try again."<<endl; 
     return false; 
    } 
    else if (g>n) { 
     cout<<"Your guess is too high. Try again."<<endl; 
     return false; 
    } 
    else { 
     cout<<"Congrats! You win. The number was "<<n<<endl; 
     return true; 
    } 
}