rand
function
int rand ( void );
Returns a pseudo-random integral number in the range 0 to 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 srand.
RAND_MAX is a constant defined in
A typical way to generate 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:
( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
Notice though that this modulo operation does not generate a truly uniformly distributed random number in the span (since in most cases lower numbers are slightly more likely), but it is generally a good approximation for short spans.
Parameters
(none)Return Value
An integer value between 0 and RAND_MAX.Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Output:
Guess the number (1 to 10): 5 The secret number is higher Guess the number (1 to 10): 8 The secret number is lower Guess the number (1 to 10): 7 Congratulations! |
In this example, the random seed is initialized to a value representing the second in which the program is executed (time is defined in the header
No comments:
Post a Comment
Thank you