How do I generate a random number in C programming such that the random seed no. srand() has a value that changes each time the program is run? Can any one type a simple function that generates a random number between 0-9?
Also, what can I use to compile the programme? And how do I run it?
Thanx.
How to generate random number in C?
Modifying the example in the Visual C++ help to adjust to your range:
#include %26lt;stdlib.h%26gt;
#include %26lt;stdio.h%26gt;
#include %26lt;time.h%26gt;
void main( void )
{
int i;
/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i %26lt; 10;i++ )
printf( " %d\n", 10 * rand() / (RAND_MAX + 1) );
}
Reply:if you want to get numbers between 0 and 9, MOD the number by 10, any number mod 10 is between 0 and 9 by definition, so
int random;
random = rand() % 10;
will set random to a number between 0 and 9, remember you're talking about the REMAINDER after dividing by 10.An equal number of random numbers will have remainders of 0,1,2,3...or 9.
Reply:You'll need to include the math library:
include %26lt;math.h%26gt;
Then just use:
x = rand(4,77); // random number between 4 and 77.
done!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment