-3
#include <iostream>
#include <string>

#include <time.h>

using namespace std;

class A{
    int x;
    public:
    void setX(){
        srand( time(NULL));
        x = rand() % 15;    
    }
    int getX(){
        return x;
    }


};

int main()
{
    A dizi[5];
    for(int i = 0; i < 5;i++){
        dizi[i].setX();
        cout<<dizi[i].getX()<<endl;
    }
}

or

#include <iostream>
#include <string>
#include <time.h>

using namespace std;

class A{
    int x;
    public:
        void setX(){
            srand( time(NULL));
            x = rand() % 15;    
        }
        int getX(){
            cout<<x<<endl;
        }    
    };

    int main()
    {
        A dizi[3];
       dizi[0].setX();
       dizi[1].setX();
       dizi[2].setX();
       dizi[0].getX();
       dizi[1].getX();
       dizi[2].getX();
    }

x is always printing the same value. How can I assign different random values to each object of the array.

I've tried srand(time (0)) and srand(time (NULL))

but they didn't work.

every class instance produces same random value, why?

hahahakebab
  • 328
  • 7
  • 22

1 Answers1

3

from the C++ documentation: http://www.cplusplus.com/reference/cstdlib/srand/

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand

Think of srand() as making a list of random numbers based on the given seed. Since you keep giving it the same seed, all of the rand() calls are getting the first element in the list. The solution is just to call srand() once, and use one rand() call each time you want to assign a value to X

Yifei Xu
  • 777
  • 1
  • 6
  • 14