【问题标题】:creating multiple objects with array of structures having unique random numbers使用具有唯一随机数的结构数组创建多个对象
【发布时间】:2017-11-19 20:13:22
【问题描述】:

我正在尝试创建不同的对象,每个对象都有一组具有随机值的数字结构。编译后,我在每个对象的数组中得到相同的数字序列。
有没有办法在数组中创建具有唯一数字序列的不同对象?

    #include <iostream>
    #include <time.h>
    #include <stdlib.h>
    using namespace std;

    struct storeTwoValue
    {
            int x;
            int y;
    };


    class practice{
    public:
    storeTwoValue storageArray[10];
    void valueGenerator()
    {       srand(time(NULL));
            for (int i = 0; i< 10; i++)
            {
                    storageArray[i].x = rand()%10 +1;
                            storageArray[i].y = rand()%7 + 1;
                    }
            }

            void print()
            {
                    cout<<"x"<<"    "<<"y"<<endl;
                    for (int i = 0; i< 10; i++)
                    {
                            cout<<storageArray[i].x <<"     ";
                            cout<< storageArray[i].y << endl;
                    }
                    cout<<endl;

            }
    };

      int main()
    {
            for(int i=0; i<3; i++)
            {       practice A;
                    A.valueGenerator();
                    A.print();
            }
            return 0;
    }

【问题讨论】:

    标签: c++ arrays random


    【解决方案1】:

    srand() 调用移至main,即只执行一次。
    您使用它的方式,每个对象的调用顺序太短,至少如果您在开始时创建/初始化它们。 IE。它们全部被初始化,而time(0) 给出了相同的种子,这意味着伪随机数生成器基本上被重置(从相同的初始值开始相同的序列)。

    要验证这一点,您可以(在移动 srand 调用之前)扩展您的循环。如果需要足够的时间,以使time(0) 可靠地具有不同的值,您将看到组内具有相同值的对象组,但组间不同。

    调用srand() 应该只执行一次,更频繁地调用它不会提高随机性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2021-01-12
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多