My dear all, Hope you fine. Code: #include<iostream.h> #include<conio.h> #include<stdlib.h> main() { cout<<"\n"<<endl; for(int i=0; i<8; i++) cout<<rand() << endl; cout<<"RAND_MAX = "<<RAND_MAX<< endl; getch(); return 0; } Output: 346 130 10982 1090 11656 7117 17595 6415 RAND_MAX = 32767 Here is my code and its output. I am trying to generate random number as you see by for loop i<8, so my output contains 8 random numbers. Whenever I run program it generates the same output list as I posted above, every time I run. Now my question is why rand() generates the same output list at every run? Why don't it change the list of 8 random numbers? And in last line what is RAND_MAX = 32767? Can you explain for me please. Thanks.
To get rand to return different numbers you must first seed the random number generator by calling srand(). See this link: srand(). That is the maximum value that your version of rand() can return. See this link: RAND_MAX Jim
You said,"You must first sees". Please tell me what do you mean by this statement? Means what is seed? & what is srand() function? And also if RAND_MAX is return maximum value that my version supports then on other operating system this returned value must be different. Am I right?
Code: //rand example #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { //rand returns a number in the range 0 to RAND_MAX //RAND_MAX is a constant defined in <cstdlib.h> //its default value may very between implementations //but it is guaranteed to be a least 32767 //srand is used to populate the random numbers returned by rand //initialise random seed srand(time(NULL)); for(int nLoop = 0; nLoop < 8; nLoop++) cout << rand() << endl; return 0; } Hope the above code helps with your understanding of random number generating and the value of RAND_MAX
Yes, you information helped me, but please tell me what is seed? what do you mean by seed? I don't understand by seed.
Let me see if i can explain it more clearly rand returns a sequence of apparently non-related numbers each time it is called. The algorithm uses a seed to generate the series of numbers, which should be initialized to some distinctive value using srand. In non tech speek srand gives rand it's starting point for random number generation Hope this explains it more for you
Please read the following link. It should explain srand(). srand Yes it can be different. On my system it returns 2147483647. Jim
Ok thanks I got your point. Now what is this that when I enter seed value as 1 then I got the same answer as the output given by my program that uses rand() function. ut as I enter different seed value I get different output. Why at 1 I am getting same answer as given by rand() function & the output is different at any other seed value? Why it is so?