Rand Function
The C++ library with header file <cstdlib> contains a random number functionnamed rand. Rand function is making a Random number; however, the output is not completely random and mix the output with time function to receive a complete random number.
For example to make a random number between 0 to 10 (less than 10 ) you can use this method:
int i;
for (i = 0; i < 10; i++) cout << rand( ) << endl; |
A sequence of pseudorandom numbers is usually determined by one number known
as the seed.
Example 2 :
For this example I seed the srand with a number 99 . It can be any number , but usually mixing srand function with a current time will help to find a better random number.
int i;
srand(99); for (i = 0; i < 10; i++) cout << (rand( ) % 11) << endl; srand(99); for (i = 0; i < 10; i++) cout << (rand( ) % 11) << endl; |
No comments:
Post a Comment