+ 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..?

30th Apr 2017, 10:42 AM
urvi
3 Answers
+ 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.
30th Apr 2017, 11:01 AM
Burey
Burey - avatar
+ 5
because you initialize srand with same value yse current system time instead srand(time(NULL)); might need to include <ctime>
30th Apr 2017, 10:49 AM
Burey
Burey - avatar
0
okay
30th Apr 2017, 10:53 AM
urvi