查找最大元素的索引 [英] Find the index of the largest element

查看:51
本文介绍了查找最大元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码的问题是它不能识别我的函数,我不确定该函数是否不正确或使用错误的语法编写.我尝试过的是为最大索引的位置创建一个新的数组,但是它似乎不起作用.

The problem with my code is that it is not identifying my function, I am not sure if the function is incorrect or written with the wrong syntax. What I have tried is to create a new array for the location of the largest index but it doesn't seem to work.

#include <iostream>
#include <iomanip>

using namespace std;

void locateLargest(const double a[][4], int location[]);

const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;

int main(){

    int location [ROW_SIZE][COLUMN_SIZE];

    double matrix [ROW_SIZE][COLUMN_SIZE];

    double input;

    cout<<"Enter the array: "<< endl;
    
    for (int i = 0; i < ROW_SIZE; i++){
        for(int j = 0; j < COLUMN_SIZE; j++){
            cin>>input;
            matrix[i][j] =  input;
        }
    }

     for(int i = 0; i < ROW_SIZE; i++){
        for(int j = 0; j < COLUMN_SIZE; j++){
            cout<< setw(4)<<matrix[i][j]<< " ";
        }
         cout<< endl;
    }

    locateLargest(matrix, location)
}

推荐答案

您可以在遍历矩阵时跟踪最大值的索引.

You can keep track of the max value's indices while iterating through the matrix.

void max_idx(const double (&arr)[RS][CS]) {
  double curr_max = arr[0][0];
  size_t max_i = 0, max_j = 0;

  for (size_t i = 0; i < RS; ++i) {
    for (size_t j = 0; j < CS; ++j) {
      if (curr_max < arr[i][j]) {
        curr_max = arr[i][j];
        max_i = i;
        max_j = j;
      }
    }
  }
  cout << "Largest value is at (i=" << max_i << ", j=" << max_j << ")\n";
}

演示

这篇关于查找最大元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆