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

时间:2014-10-02 10:10:37

标签: c++ random

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

//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;
}

1 个答案:

答案 0 :(得分:3)

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