随机数生成器游戏

时间:2019-04-06 07:59:21

标签: c++

#include <iostream>
#include <stdlib.h>

using namespace std;

void Guess(int Answer,int guess)
{
    if(guess!=Answer)
    {
        if(guess<Answer && guess!=Answer)
        {
            cout<<"The number is higher, try again"<<endl;
            cin>>guess;
        }
        else
            if(guess>Answer && guess!=Answer)
                {
                    cout<<"The number is lower, try again"<<endl;
                    cin>>guess;
                }
    }

}

int main()
{
    int Answer,guess;
    Answer=rand()%100;
    cout<<Answer<<endl;
    cout<<"Guess the number from 1 to 100"<<endl;
    cin>>guess;
    while(Answer!=guess)
       {
            Guess(Answer,guess);
            if(Answer==guess)
                break;
       }
       if(guess==Answer)
        cout<<endl<<"Congratulations, you guessed the number, it was "<<Answer<<" !";
}

因此,这是我学习一些基本功能之后编写的代码,您可能会说应该生成一个随机数,然后您必须猜测数字是多少,但是我有一些问题:

  1. 它生成相同的随机数
  2. 如果您第一次没有猜对,那么即使您在某个时候猜到了数字,代码也会一直持续下去。
  3. 如果您猜出一个更大的数字,比如说50,而答案是40,即使您然后猜到30,它仍然说该数字应该说的更低。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

void Guess(int Answer,int guess)更改为void Guess(int& Answer,int& guess),并在int main的开头添加了srand ( time(NULL) );,以防止生成相同的数字