首页 > 解决方案 > 如何在二维数组中找到用户输入单元格周围的单元格总和?

问题描述

这是我到目前为止所拥有的,为了便于计算,省略了 srand(0),除了外部限制之外,这些值都很接近。输出的格式都是正确的,但如果所选单元格位于第 9 列或第 9 行,则周围单元格的总和值通常为数百万。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{

    int matrix[9][9];
    int row_n, col_n, sum, surround_sum, i, j;
    cout << "\t    columns" << endl;
    cout << "       1 2 3 4 5 6 7 8 9 " << endl;
    for (int i = 0; i < 9; i++)
    {
        cout << "row " << i + 1 << "  ";
        for (int j = 0; j < 9; ++j)
        {
            matrix[i][j] = rand() % 10;
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << "what array cell would you like to see? (press enter after each entry)" << endl;
    cout << "row = ";
    cin >> row_n;
    cout << "column = ";
    cin >> col_n;

    cout << "the number " << matrix[row_n - 1][col_n - 1] << " is in cell " << row_n << "," << col_n << endl;

        for (int i=(row_n-2);i<(row_n+1);i++){

            for(int j=(col_n-2);j<(col_n+1);j++){
                if (i>9||i<0)
                    i=0;
                if (j>9||j<0)
                    j=0;
                sum+=matrix[i][j];
                surround_sum= sum-matrix[row_n-1][col_n-1]+2;
            }}
    cout << "the sum of the cells surrounding cell " << row_n << "," << col_n << " is " << surround_sum;

    return 0;
}

标签: c++

解决方案


推荐阅读