我有一个模拟骰子游戏的任务。作为该程序的一部分,用户输入掷骰子的数量以及掷骰子的次数。如果用户滚动4个骰子,程序应该将这4个值相加,将结果存储在一个数组中,然后按照用户定义的次数重新执行程序。主代码和函数原型是由我们的导师定义的,不能修改。我们必须写这个函数。从函数获取二维数组,返回一个int C++
在主的步骤3中,有两个用于循环。内循环调用有问题的函数。二维数组rollSums [] []被分配给函数的结果。这个数组将被用在另一个函数中。我无法弄清楚如何从函数中正确地填充二维数组。代码和我在函数尝试低于:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int sum;
int rollSums[MAXNUMTOROLL][MAXROLLS];
int diceVals[MAXROLLS];
double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numToRoll, numRolls;
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
do
{
cin >> numToRoll;
} while (numToRoll < 0 || numToRoll > MAXNUMTOROLL);
cout << "Please enter the number of rolls:" << endl;
// STEP 2: Ask user to input the number of rolls to carry out:
do
{
cin >> numRolls;
} while (numRolls < 0 || numRolls > MAXROLLS);
// STEP 3: For k=1 to numToRoll, simulated numRolls rolls of the dice
// and store the sum of the numbers rolled in the array rollSums[][]
for (int k=1;k<=numToRoll;k++)
{
for (int i=0;i<numRolls;i++)
{
rollSums[k-1][i] = rollDice(diceVals, k);
}
}
return 0;
}
int rollDice(int diceVals[], int numToRoll) //function simulating throwing of dice
{
int sum=0;
int i=0;
for(i=0;i<numToRoll;i++)
{
diceVals[i]=1+rand()%6;
sum=sum+diceVals[i];
}
return sum;
}
你有预期产出的例子吗?你的第3步循环卷每个单独死亡。所以当k = 1时,你将掷出1 numRolls次。当k = 2时,您将为die 2执行相同操作。然后,您还将k的值传递给rollDice函数。我的理解是,如果用户想掷4个骰子,那么你将所有4个掷在一起并存储该总和。但这不是你的代码所做的。你能澄清吗? – Pete 2012-03-28 17:16:53
@Pete如果我滚2个骰子3次我应该有一个像输出:无骰子的掷骰:1 2卷1:4 8卷2:3 9卷3:4 10 – adohertyd 2012-03-28 19:22:07
很抱歉,如果我是一个小致密但我仍然不遵循。祝你好运! – Pete 2012-03-29 01:37:10