c++ - 如何在二维数组 C++ 中找到最大值输入的索引
问题描述
我在尝试找到最大元素的索引时需要帮助。用户首先输入二维数组的大小,然后用户输入数组中的元素。然后程序将显示最大数组的位置。
但是,我在下面有这段代码,并且在打印出数组中最大元素的索引位置时遇到了麻烦。它只是返回为 0,0。
#include<iostream>
using namespace std;
int main()
{
int row, column;
int r,c;
cout << "Enter the number of rows of the array: ";
cin >> row;
cout << "Enter the number of column of the array: ";
cin >> column;
cout << "\nEnter the array: " << endl;
double table[row][column];
for ( r = 0; r < row; r++) {
for ( c = 0; c < column; c++) {
cin >> table[row][column];
}
}
int rr=0,cc=0;
int max;
for ( r = 0; r < row; r++){
if (table[rr][cc] < table[r][c]) {
rr=r;}
for ( c = 0; c <column; c++){
if (table[rr][cc] < table[r][c]) {
cc=c;
}
}
}
cout << "\nLocation of the largest array: " << rr << ","<< cc << endl;
}
解决方案
您应该首先移动r
并c
搜索满足的元素,然后检查元素是否满足条件。
for ( r = 0; r < row; r++){
// remove this, or you will access out-of-range because c will be column here
//if (table[rr][cc] < table[r][c]) {
// rr=r;}
for ( c = 0; c <column; c++){
if (table[rr][cc] < table[r][c]) {
rr=r; // also update rr here
cc=c;
}
}
}
此外,正如@Jarod42 指出的那样,输入部分cin >> table[row][column];
也是错误的。它应该是cin >> table[r][c];
,否则将在那里调用另一个超出范围的访问。
推荐阅读
- assembly - 零扩展立即值以适合寄存器
- c# - Roslyn:将 using 语句添加到语法树
- python - Python pandas如何将df:列值转换为行值?
- c++ - A类中的B类继承A类
- python - (-212:Parsing error) 使用 yolo、google colab 和 opencv 进行对象检测
- javascript - 使用 Fabric JS 定义标记线
- sql - SQL 在 2 个单独的列中从 2 个单独的行中减去一个值
- ruby-on-rails - Rails 验证错误消息删除键
- google-cloud-endpoints - 如何在服务器端运行可以通过 Google Cloud Endpoints 创建新文件的按需脚本?
- report - Cognos 结果按 day_of_week/工作日