Pages

Sunday, October 7, 2012

Generating random numbers in c++


#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
 int c;
 srand(time(NULL));
        while(1)
        {
       cout<<rand();
        }
 return 0;
}

Lets have an in depth look at the code. The actual random numbers are generated by the rand() function. The numbers that it generates are not random but are pseudorandom i.e. they appear to be random but are not. In actual the rand() function generates a predictable series of numbers. The series however can be initialized with a seed value which in the above code is being done using the srand() function. The srand() needs only be called once during a typical program. However given a same seed value the program will generate the same random numbers every time the program is run. In order to avoid this repetition across program executions. We have passed the time(NULL) as an argument to the srand() function. Which will initialize the srand with a new value every time the function is called, hence now the numbers generated by rand() would appear to be random.

No comments:

Post a Comment