-1
#include<iostream>
using namespace std;
#include<stdlib.h>

int main()
{
  cout<<rand();
}

When I run this program, it generates random number like 41. And when I run the program again, it generates the same number, i.e. 41.

But I want to generate different random number all the time when we run the program. So, please tell me, how it can be done?

phuclv
  • 37,963
  • 15
  • 156
  • 475
paras
  • 53
  • 1
  • 9
  • Have you tried smth. from examples? http://www.cplusplus.com/reference/cstdlib/rand/ – Paul T. Rawkeen Apr 24 '15 at 12:25
  • Does this answer your question? [How to generate a random number in C++?](https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c) – phuclv Apr 07 '21 at 08:20

2 Answers2

0

this sample code use the system time as a seed and use rand function to generate the random number so everytime you run this code ,you will get the different random numbers

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
  time_t t;
    /*get the system time*/
    time(&t);
    /*transfer time_t variable to integer variable and send it to the srand function*/
    srand((unsigned int) t);
    /*Generating 10 random numbers continuous*/
    for (int i = 0; i < 10; i++)
        cout<<"The random number is "<<rand()<<endl;
    cin.get();
    return 0;

}
Parth Akbari
  • 641
  • 7
  • 24
  • In some programs , they use time(NULL). So is there any difference in t=time(NULL) and time(&t) – paras Apr 24 '15 at 12:02
  • The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable. – Parth Akbari Apr 24 '15 at 12:08
0

Try initalising the random seed:

/* initialize random seed: */
  srand (time(NULL));

http://www.cplusplus.com/reference/cstdlib/rand/

phuclv
  • 37,963
  • 15
  • 156
  • 475
Tony Weston
  • 317
  • 2
  • 9
  • What is seed? I have read that it initialise the value. Which value it is actually initialising? – paras Apr 24 '15 at 12:05
  • Without special hardware, it is impossible for a computer to generate a random number. If you ask a computer to run any algorithm, then it will run it identically, and get the same answer every time. It is in effect impossible to generate a truly random number. However, one way of getting apparently random numbers is to keep the result of the previous calculation, and start the next random calculation from that. This way you get a sequence of random numbers. The first time you run this however, it will always give the same result. So, a 'seed' number is used to start the sequence. – Tony Weston Apr 24 '15 at 13:19