-1

I am trying to generate random numbers (1 to 6), but every time I run my program I always get the same two numbers. Here is the code:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// function prototype
int random();

// main function
int main()
{
    int rand1=random();
    int rand2=random();
    cout << rand1 << endl;
    cout << rand2 << endl;

    cin.get();
    return 0;
}

//function definition
int random()
{
    const int MAX_NUMBER = 6;
    const int MIN_NUMBER = 1;
    unsigned seed=time(0);
    srand(seed);

    int randomNumber;
    randomNumber=(rand() % (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER;


    return randomNumber;
}

I'm not sure what is wrong and why I always get the same two random numbers.

Alex Johnson
  • 958
  • 8
  • 23
quantum
  • 17
  • 2

1 Answers1

2

Notice :

rand() returns a random positive integer in the range from 0 to 32,767. This function can be thought of as rolling a die with 32,767faces.

The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers. Since the same sequence is generated each time the seed remains the same, the rand() function generates a pseudo-random sequence.

To prevent the same sequence from being generated each time, use srand(x) to change the seed value.

Sample program :

/*generate 10 random numbers between 1 and 6 inclusive, without repetition of the sequence between program runs*/

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
     // to prevent sequence repetition between runs     
     srand(time(NULL));  


     for(int i = 1; i <=10; i++)     // looping to print 10 numbers
     {
           cout<< 1 + rand( ) % 6;   // formula for numbers 
     }

     return 0;
}
  • *rand() returns a random positive integer in the range from 0 to 32,767. This function can be thought of as rolling a die with 32,767 faces.* Isn't exactly true. `RAND_MAX` has to be at least `32,767`. On my machine for instance `RAND_MAX` is `2,147,483,647` – NathanOliver Jul 17 '18 at 16:19