rand()在编译时生成相同的数字

Bug*_*ter 10 c++ random

可能重复:
在C++中使用rand()函数的正确方法是什么?

我一直在学习如何使用rand()函数,我在C++中编写了一个小猜谜游戏,如下所示,但问题是,无论编译程序多少次,生成的数字都是相同的 - > 41

#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;

int main()
{
    int x = rand()%100;
    int y=0;
    cout << "Ghiceste numarul!" << endl;
    cin >> y;

    while(y != x) {

         if(y > x) {
            cout << "Numarul tau este prea mare! Incearca un numar mai mic!" << endl;
            cin >> y;
          }

             if(y < x) {
                 cout << "Numarul tau este prea mic!" << endl;
                 cin >> y;
               }

      if (y == x) {
      cout << "FELICITARI, AI GHICIT NUMARUL!\n";
      return 0;
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试改变rand()的最大值,只要我把它改为<41就改变了.

有任何想法吗?我没有线索,为什么发生这种情况.我正在使用CodeBlocks IDE,我尝试重建(CTRL + F11)

Ada*_*m S 12

尝试添加

srand(time(0));
Run Code Online (Sandbox Code Playgroud)

在开始时main.

  • 这样做,但请注意,您只需要在程序开始时执行一次.每次调用`rand()`时都不要这样做. (7认同)
  • 并注意警告:如果你每秒运行你的程序超过一次,它将重新使用随机种子(并在每次运行程序时给你相同的数字,直到第二次通过). (5认同)

Ant*_*cus 5

您应该首先尝试初始化rand()函数的种子,如下所示:

srand (time(NULL))
Run Code Online (Sandbox Code Playgroud)

在开始时main.确保在标题中包含time.h

#include <time.h>
Run Code Online (Sandbox Code Playgroud)

要么

#include <ctime>
Run Code Online (Sandbox Code Playgroud)