【发布时间】:2020-02-11 00:12:27
【问题描述】:
找出同时掷出几个无偏骰子时不同总值的概率。该程序使用了各种技术,包括基本 I/O、算术、条件控制结构、循环和数组。
详情请访问https://drive.google.com/file/d/1gf10Pi_ME2jpmMM4_Y62-gkZ3we_llyy/view?usp=sharing。
我正在使用二维数组来完成这项工作。但是,继续下去就不行了,输出了“超出范围”的问题。
#include <iostream>
using namespace std;
int main()
{
//Initialise the variables
int number;
cout << "Input the number of dice(s): ";
cin >> number;
//Initialise 2d array and set number as the row
int face[20][20];
for (int i = 0; i < number; i++) {
cin >> face[i + 1][20];
}
//Initialise 2d array and set input value as the column
int value;
for (int i = 0; i < number; i++) {
//Consider the output statement of the number of faces for dice
switch (number + 1) {
case 1:
cout << "Input the number of the faces for the " << number + 1 << "st" << " dice: ";
break;
case 2:
cout << "Input the number of the faces for the " << number + 1 << "nd" << " dice: ";
break;
case 3:
cout << "Input the number of the faces for the " << number + 1 << "rd" << " dice: ";
break;
default:
cout << "Input the number of the faces for the " << number + 1 << "th" << " dice: ";
}
cin >> face[i][value];
}
//calculate the sum of the dice
int sum = 0;
for (int i = 0; i < number; i++) {
sum = sum + face[i][value];
}
//initialise the base value (max probability) of the dice
int base;
for (int i = 0; i < number; i++) {
base = base * face[i][value];
}
//Output statement
if (number < 10) {
for (int i = number; i < sum; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
}
else {
for (int i = number; i < 10; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
for (int i = 10; i < sum; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
}
return 0;
}
//Calculating the probability
int probability(int number, int base, int face[20][20])
{
int probability = 0;
int rollresult = face[0][0];
while (rollresult == number) {
for (int i = 0; i < number; i++) {
for (int j = 0; j; j++) {
rollresult = face[i][j] + rollresult;
}
}
probability++;
}
return probability;
}
错误信息:
In function 'int main()':
51:69: error: 'probability' was not declared in this scope
56:70: error: 'probability' was not declared in this scope
59:70: error: 'probability' was not declared in this scope
【问题讨论】:
标签: c++ multidimensional-array probability dice