如何在2D数组中返回最大值(总计后)? [英] How do I return the largest value (after total) in 2D array?

查看:75
本文介绍了如何在2D数组中返回最大值(总计后)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi, 

I am trying to find the largest value in a 2D array. The 2D array has been populated with numbers that has been entered by users. Each row represents a 'topic'. The function below should loop through the array starting with its row and 10 columns and totalling the result. 

Please note: I am going through an old C++ book that uses arrays as opposed to improved containers.

Thank you in advance!! :)





我尝试过:





What I have tried:

int getHighest(int arr[][10])
{
    int total = 0;
    int index;
    int largest = 0;
    
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if (responses[i][j] >= 1)
            {
                index = j + 1;
                total += (index * (responses[i][j]));
            }
        }
        if (total > largest)
        {
            largest = total;
        }
    }

    return largest;
}

推荐答案

if 条件移入内循环,并更改它,以便比较和使用数组单元格而不是总计

想一想:除非您的数组包含大量负数,否则总数将始终与最大值相同或更大...
Move your if condition into the inner loop, and change it so it compares and uses the array cell instead of total.
Think about it: unless your array contains a significant number of negative numbers, the total will always be the same or bigger than the largest value...


这篇关于如何在2D数组中返回最大值(总计后)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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