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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With