mercredi 1 novembre 2017

C++ create object array same random value

    #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();
    }

always x printing same value how to assing different random value each object array? I try everthing srand(time (0)) or srand(time (NULL)) not work. I search from internet this issue but I cant find any solution.

every class instance produces same random value, why?

Aucun commentaire:

Enregistrer un commentaire