模拟两个骰子的滚动并保存在矢量中

Simuate Rolling Of Two Dice and Save Sum In Vector

本文关键字:保存 滚动 存在 两个 模拟      更新时间:2023-10-16

我正在尝试制作此代码,以滚动两个骰子并跟踪向量中的总和。我想出了以下代码,但是如果我输入以上的数字12。

#include "std_lib_facilities.h"
void simulate(vector<int>&, size_t);
void size_int(const vector<int>, size_t);
void print_vector(const vector<int>&, size_t);
int main()
{
    size_t n;
    cout << "Enter the amount of rolls: ";
    cin >> n;
    vector<int> v(12);
    for(int i=0;i<v.size();i++)
    {
        v[i] = 0;
    }  
    simulate(v, n);
    print_vector(v, n);
}
void simulate(vector<int>& sum, size_t n)
{
    int dice_1, dice_2;
    cout << "Rolling the dice " << n << " times produces:n";
    srand( time(NULL) ); 
    size_t i;
for ( i = 0; i < n; ++i){
    dice_1 = 1+(rand() % 6); 
    dice_2 = 1+(rand() % 6);
    sum[dice_1+dice_2]++;
    }
}
void print_vector(const vector<int>& v, size_t n)
{
    size_t i;
    double x = 1.0*n;
    cout << "RolltFrequencytProbablityn";
    for(i = 1;i<v.size();++i)
    {
        cout << i+1 << "t" << v[i] << "tt" << v[i]/x << endl;
    }
}

sum[dice_1+dice_2]++;

dice1+dice2将是2至12(包括12)的值。sum仅具有元素0至11包含元素。您需要大小sum 13 才能做到这一点。

当您的向量从0开始您应该将值存储到

sum[dice_1+dice_2-1]++;

并在打印时。

开始
for(i=0....)