可能重复:
在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()函数的种子,如下所示:
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)