rand() generating same number upon compilation
Solution 1
Try adding
srand(time(0));
at the beginning of main
.
Solution 2
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>
Solution 3
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.
Related videos on Youtube
Bugster
I'm no longer active due to the exagerated moderation of this site. Moderation is great but after seeing questions of over 500 votes be closed because they're not constructive, I've come to question it. What if some day all closed questions get purged?
Updated on June 04, 2022Comments
-
Bugster almost 2 years
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)
-
spencercw about 12 yearsDo this, but be aware you only need to do it once at the beginning of your program. Don't do it every time you call
rand()
. -
Brendan Long about 12 yearsAnd be aware of the caveat: If you run your program more than once per second, it will re-use random seeds (and give you the same numbers every time you run the program until a second passes).
-
Adam S about 12 yearsBoth good points. Be sure to check out the SO post referenced in tenfour's comment to your question.