Thursday, July 9, 2009

How do you get a random in c programming language?

ex.I want to generate a random number.

How do you get a random in c programming language?
First you have to seed the random number generator.





srand(time());





then to get a random number between 0-9.


int randnumber;


randnumber = rand() % 10;
Reply:1st, include time.h %26amp; stdlib.h


2nd, initialize random number generator: 'randomize ();', defined in the above header files


3rd, to store a random number in an integer variable x:


'x = random (max);'


'random' returns a random integer from 0 to max-1, and stores it in x.
Reply:Most compilers return a value between 0 and 1. So, if you want an integer, you multiply the output of the rand function by the upper limit you want. If you want a number from 0 to 10, MyVal = 10 * rand();
Reply:randomNumber = rand();
Reply:Have a look at this C programming tutorial for generating random numbers.
Reply:n = rand(i);





where i is the seed integer and n is the random integer returned by the function.
Reply:#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;





int main(void)


{


int i;





printf("Ten random numbers from 0 to 99\n\n");


for(i=0; i%26lt;10; i++)


printf("%d\n", r a n d() % 100);//to keep it below 100


//r a n d() generates nos. 0(zero) and above i.e no negetive nos.


//r a n d : is a single word without blanks inbetween the letters


return 0;


}


No comments:

Post a Comment