c++ - 关于骰子概率和二维数组的问题
问题描述
找出同时掷出几个无偏骰子时不同总值的概率。该程序利用各种技术,包括基本 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
解决方案
问题是您试图在probability()
声明之前调用该函数!您可以在之后保留实际定义,main
但您需要在更早的时候对其进行“转发”声明。尝试在'main'之前插入一个声明,因此:
int probability(int number, int base, int face[20][20]);
int main() {
...
推荐阅读
- angular - 角routerlink链接在sb admin 2 bootstrap 4模板的侧边栏中不起作用
- c# - Fiddler 不使用“GetAsync”捕获流量
- here-api - HERE Routing API - 如何使用带有多个航路点的 publicTransportTimeTable 模式使用计算路线资源?
- git - 如何在 Git 中创建仅包含来自特定提交的文件的基线
- azure - Azure Devops:值不能为空,参数令牌
- php - 使用 JQuery 和 AJAX 将文件数据发送到文件输入元素
- angular - 如何修复我的数据没有从 Angular 中的服务到模块
- reactjs - 如何创建闪烁的反应视图
- google-cloud-platform - http负载均衡器和健康检查
- ios - didSelectRowAt 没有被调用,但委托和数据源已设置