使用具有唯一随机数的结构数组创建多个对象
creating multiple objects with array of structures having unique random numbers
我正在尝试创建不同的对象,每个对象都有一个带有随机值的数字结构数组。编译后,我在每个对象的数组中都得到了相同的数字序列。
有没有办法在数组中创建具有唯一数字序列的不同对象?
#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;
}
将srand()
调用移动到 main 中,即只执行一次。
你使用它的方式,每个对象的调用顺序太短,至少如果你在开始时创建/初始化它们。即它们全部初始化,而time(0)
给出相同的种子,这意味着伪随机数生成器基本上是重置的(从相同的初始值开始相同的序列(。
要验证这一点,您可以(在移动 srand 调用之前(扩展您的循环。如果花费足够的时间,以便time(0)
可靠地具有不同的值,您将看到组中具有相同值但不同组的对象组。
调用srand()
应该只执行一次,更频繁地调用它不会提高随机性。
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?