gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:23:39 25 4
gpt4 key购买 nike

<分区>

我编写了这段代码来模拟掷 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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com