+ 2
Srand
#include <iostream> #include <cstdlib> using namespace std; int main () { srand(98); for (int x = 1; x <= 10; x++) { cout << 1 + (rand() % 6) << endl; } } Why this code giving output 5 always..?
3 Réponses
+ 6
a little explanation about srand:
the function srand takes an integer value and through some manipulations produces a random number through some calculations.
therefore, if given the same value, the calculations will be the same, resulting the same output.
by giving time(NULL) which is the current system time in seconds, the result will be different for each second that passes as the time will be different and the calculations will also be different.
+ 5
because you initialize srand with same value
yse current system time instead
srand(time(NULL));
might need to include <ctime>
0
okay