首页 > 解决方案 > 如何在二维数组 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;
    
}

标签: c++arraysindexing

解决方案


您应该首先移动rc搜索满足的元素,然后检查元素是否满足条件。

    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];,否则将在那里调用另一个超出范围的访问。


推荐阅读