Possible Duplicate:
What's the Right Way to use the rand() Function in C++?
I've been learning how to use the rand() function and I wrote a small guessing game in C++ as seen bellow, but the problem is, no matter how many times I compile the programs the generated number is the same -> 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;
}
}
}
I also tried to change the max value of rand() and it did change as long as I put it < 41.
Any ideas? I don't have a clue as to why this is happening. I am using CodeBlocks IDE and I tried rebuilding (CTRL+F11)
Try adding
srand(time(0));
at the beginning of main
.
You should try first to initialize a seed for the rand() function as follows:
srand (time(NULL))
at the beginning of main
. Make sure to include the time.h in the header
#include <time.h>
or
#include <ctime>
it's probably using the same seed each time for the random number generator. if you set the seed of the random number generator each time to a different value, you will get different numbers. according to the docs:
In order to generate random-like numbers, srand is usually initialized
to some distinctive value, like those related with the execution time.
For example, the value returned by the function time (declared in
header ) is different each second, which is distinctive enough
for most randoming needs.
You need to pass a seed to the rand() function which will be different each time the program is run (e.g. timestamp). Generally speaking, generating truly random numbers isn't possible but you can get a pseudo-random.
The random number generator is being seeded with the same default state on each run of your program.
In order to get different results on each run, you need to seed the random number generator in your program by calling srand()
and passing in a new seed. It's common to use the return value of time(NULL)
as the seed, as that will guarantee that you get a different seed on different runs of you program.
So add the following at the beginning of main
:
srand(time(NULL));
You need to seed the rand function with srand() at the beginning of main
, typically using time(); function