How is it showing different numbers in this program and the same number again and again in the previous program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How is it showing different numbers in this program and the same number again and again in the previous program

About the program

21st Jun 2017, 5:54 AM
Christine​ Thomas
3 Answers
+ 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; }
21st Jun 2017, 6:26 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Excuse me. Which program in particular?
21st Jun 2017, 6:14 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
The programs in the first two lesson of the rand() function in C++
21st Jun 2017, 6:16 AM
Christine​ Thomas