+ 1
How is it showing different numbers in this program and the same number again and again in the previous program
About the program
3 Réponses
+ 7
That's not it. The program in the second slide is showing "different" numbers because a loop is used to generate multiple numbers. However, they are not different. You will still get the same numbers from rand() for each run.
Seeding the RNG algorithm is required to produce different numbers from rand() output. This is achieved by srand() function. The most common seed used is current system time, time().
srand(time(0));
By adding this line to your program, you seed the RNG algorithm with system time (which is constantly changing, and hence rand() will return different numbers for each run.
E.g.
Compare:
#include <iostream>
#include <cstdlib>
int main()
{
std::cout << rand();
return 0;
}
and
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand(time (0));
std::cout << rand();
return 0;
}
+ 5
Excuse me. Which program in particular?
+ 1
The programs in the first two lesson of the rand() function in C++