首页 > 解决方案 > 关于骰子概率和二维数组的问题

问题描述

找出同时掷出几个无偏骰子时不同总值的概率。该程序利用各种技术,包括基本 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-arrayprobabilitydice

解决方案


问题是您试图在probability()声明之前调用该函数!您可以在之后保留实际定义,main但您需要在更早的时候对其进行“转发”声明。尝试在'main'之前插入一个声明,因此:

int probability(int number, int base, int face[20][20]);

int main() {
    ...

推荐阅读