how do u use the random function in c........?
i want the function to generate values between a specific range of values........
How to use random functions in 'c' language?
The rand() function will always return a value between 0 and an implementation-defined quantity, RAND_MAX. To use rand() to produce integers in the range from x
to y, inclusive, you should use something like:
/* initialize random generator */
srand ( time(NULL) );
int result = x+(int) ((y -x +1) * (double)rand()/(RAND_MAX + 1.0));
____________________
/*Alternative: Use the modulus operator (%) to bring the number in range.*/
printf ("A number between 0 and RAND_MAX : %d\n", rand());
printf ("A number between 0 and 99: %d\n", rand() % 100);
printf ("A number between 0 and 9: %d\n", rand() % 10);
Reply:#include %26lt;time.h%26gt;
#include %26lt;stdlib.h%26gt;
main()
{
srand(time(0));
int random=rand()%255+1; //from 1 to 255
}
Reply:#include %26lt;time.h%26gt;
#include %26lt;stdlib.h%26gt;
int main()
{
srand((unsigned)time(0));
int random=rand()%10+1; //from 1 to 10
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment