Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand() generating same number upon compilation [duplicate]

Tags:

c++

random

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)

like image 300
Bugster Avatar asked Feb 23 '12 21:02

Bugster


1 Answers

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>
like image 93
AntiClimacus Avatar answered Oct 14 '22 23:10

AntiClimacus