2017-07-12 184 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; 
    } 
}