#include <iostream> #include <ctime> using namespace std; class massive { private: int b[4]; public: massive() { srand(time(0)); for (int i = 0; i < 4; i++) { b[i] = 1 + rand() % 10; cout << b[i] << " "; } cout << "\n"; } }; int main() { massive a; massive b; return 0; } 

Why when executing the code, both arrays are constantly initialized (or, at least, displayed on the screen) with the same numbers? https://www.onlinegdb.com/edit/B1wiCeG2m

  • srand needs to be called once, and not before each sequence of rand calls. - Croessmah
  • one
    time(0) returns the time in seconds, so in almost all launches the value passed to srand() will be the same. - avp

1 answer 1

This happens because srand (time (0)); you need to call in the main function, then you will have different values.

Here is the working code.

 #include <ctime> #include <iostream> using namespace std; class massive { private: int b[4]; public: massive() { for (int i = 0; i < 4; i++) { b[i] = 1 + rand() % 10; cout << b[i] << " "; } cout << "\n"; } }; int main() { srand(time(0)); massive a; massive b; system("pause"); return 0; } 

enter image description here