c++ - 如何在二维数组中找到用户输入单元格周围的单元格总和?
问题描述
这是我到目前为止所拥有的,为了便于计算,省略了 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;
}
解决方案
推荐阅读
- linux - 无法在 linux 上编译“http”rust crate
- java - 运算符不存在:字符变化 =?,postgres JDBC 占位符不起作用
- java - 即使使用 values-night 也无法在我的应用程序中禁用夜间模式
- javascript - Javascript:如何将获取的返回值存储到全局变量中?
- matlab - 替换落在Matlab中三角形内的值
- node.js - Mongoose 预保存中间件错误是空对象
- sql - 两个表的内连接,另一个表的左连接结果
- android - 无法在 osmdroid 应用程序上解析符号 StyleSelector
- mysql - 无法使用 AWS Instance 进入 MySQL 终端
- angular - 如何从 Angular 的窗口身份验证中获取用户名?