我创建了以下函数来为骰子游戏创建随机数
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "dice.h"
#include "display.h"
using namespace std;
int die[6][10];
void dice(int times, int dice){
int r;
for(int x=0;x<times;x++){
for(int x=0;x<dice;x++){
srand(time(0));
r=(rand() % 5);
die[r][x]+=1;
cout<<"Die #"<<x+1<<" rolled a "<<r<<endl;
}
}
}
但它不会重新播种。它只是为每个骰子输出相同的数字。有谁知道我该如何解决它?
最佳答案
您没有正确使用 srand 和 rand 函数。您应该为随机数生成器“播种”一次,然后使用 rand()
从 RNG 检索连续值。每个种子都会产生符合特定随机性标准的特定数字序列。
相反,您每次都会播种随机数生成器,然后检索随机序列中的第一个值。自 time()
调用如此之快以至于它返回相同的种子,您实际上将随机数生成器重置回同一序列的开头,因此您得到的数字与之前获得的数字相同。
即使 time()
返回的值更新得足够快,以至于您每次都会得到一个新的种子,但仍然不能保证您获得良好的随机数。随机数生成器旨在生成数字序列,其中该序列具有某些统计特性。但是,不能保证相同的属性适用于从不同序列中选择的值。
因此,要使用确定性随机数生成器,您应该只为生成器播种一次,然后使用该种子生成的值序列。
还有一点;用于实现 rand()
的随机数生成器历史上一直不是很好,rand()
不是可重入或线程安全的,并且转换 rand()
生成的值将值转化为您想要的分布并不总是那么简单。
在 C++ 中,您应该更喜欢 <random>
库提供了更好的功能。这是使用 <random>
的示例.
#include <random>
#include <iostream>
int main() {
const int sides = 6;
int groups = 10, dice_per_group = 3;
std::uniform_int_distribution<> distribution(1,sides); // create an object that uses randomness from an external source (provided later) to produces random values in the given (inclusive) range
// create and seed the source of randomness
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 engine(seed);
for (int i=0; i<groups; ++i) {
for (int j=0; j<dice_per_group; ++j) {
// use the distribution with the source of randomness
int r = distribution(engine);
std::cout << "Die #" << j+1 << " rolled a " << r << '\n';
}
std::cout << '\n';
}
}
关于c++ - 随机骰子不重新播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12290251/