Situatie
Returns a pseudo-random integral number in the range between 0
and RAND_MAX
This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
RAND_MAX is a constant defined in <cstdlib>
A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
|
|
Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).
Solutie
/* rand example: guess the number */
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
do {
printf (“Guess the number (1 to 10): “);
scanf (“%d”,&iGuess);
if (iSecret<iGuess) puts (“The secret number is lower”);
else if (iSecret>iGuess) puts (“The secret number is higher”);
} while (iSecret!=iGuess);
puts (“Congratulations!”);
return 0;
}
In this example, the random seed is initialized to a value representing the current time (calling time) to generate a different value every time the program is run.
Leave A Comment?