c++ - 从随机生成的 0 到 1 之间的数字滚动两个骰子给定次数 C++

标签 c++ random

<分区>

我编写了这段代码来模拟掷 2 个骰子。当我只滚动 2 个骰子运行它时,它似乎给我一个 2 到 12 之间的随机数(这就是我想要的)。但是,当我尝试多次模拟滚动时(使用 for 循环),它总是将数据分箱到同一个 vector 空间中。如果我运行它的次数非常多,它就会开始有点分离。这让我认为问题出在随机种子上,但我不确定如何纠正这个问题。

//using rand to generate a uniformly distributed number between 0 and 1. Multiplying that number by 6, adding 1 to it and then rounding it down to simulate a dice throw. Rolling 2 dice together to get a total between 2 and 12, then keeping a tally of rolling 2 dice a given number of times.

#include <iostream>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#include <time.h>


using namespace std;

double rnd ()
{    
    //defining the variables as doubles
    double n;
    double y;

    //setting up the random number seed
    srand (time(NULL));

    //using the rand command to generate a pseudo-random number between 0 and 1
    n = ((double)rand()/(double)RAND_MAX);
    return n;
}

int dice ()
{
    double x = rnd()*6;
    int y = x+1;
    return y;
}


int two_dice ()
{
    int throw_1 = dice();
    int throw_2 = dice();
    int score = throw_1 + throw_2;
    return score;
}

int main ()
{
    //asking the user for the number of trials
    int n_trials;
    cout << "plese enter the number of trial that you wish to simulate \n";
    cin >> n_trials;

    //creating the vector to store the data in
    vector<int> dice_throws(11); //has 12 bins to store data in

    int sum_dice;

    //using a for loop to roll the dice multiple times
    for (int roll = 0; roll <= n_trials; roll++) {
        sum_dice = two_dice();
        dice_throws[sum_dice - 2]++;
    }


    for (int y = 0; y<dice_throws.size()+1; ++y) {
        cout << dice_throws[y] << "\n";
    }

    return 0;
}

最佳答案

你得到相同的数字是因为每次调用 rnd 函数时都会调用 srand。将 srand 移动到 main 的开头,它应该可以正常工作!

关于c++ - 从随机生成的 0 到 1 之间的数字滚动两个骰子给定次数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158672/

相关文章:

c++ - C++类中的矩阵

c++ - 析构函数调用数量超过构造函数调用

python - 获取 numpy.random 分布列表

python - Numpy:随机数生成 - 将循环分成 block

c++ - 在 C89 和 C++ 中用空参数调用宏真的是未定义的行为吗?

C++:我怎样才能重载一个函数,以便它可以接受任何仿函数,包括指向成员函数的指针?

c++ - 重载类型转换为 bool 和效率

C++11 随机数分布在不同平台之间不一致——有什么替代方案?

java - 这些随机数生成不是在 Java 中等效的范围内吗?

xslt - 在 XSLT 中随机选择一个节点