我有一個模擬骰子游戲的任務。作爲該程序的一部分,用戶輸入擲骰子的數量以及擲骰子的次數。如果用戶滾動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