打印行数以及最大行的2D数组的总和

C++ Print Row Number along with Maximum Sum of Rows 2D Arrays

本文关键字:2D 数组 打印      更新时间:2023-10-16

我试图计算2d数组中的行和,并比较行与其他行的最大和。我成功地计算了每一行的总和,并将行最大值与其他行进行了比较,但我目前面临的问题是,我不知道如何打印具有最大总和的行号。下面是我正在编写的一段代码:

void calculateMaxRowSum(int array[10][10])
{
     int maxsum = 0;
     for(int i=0;i<10;i++) 
     {  
          int sum = 0;  
          for(int j=0;j<10;j++)
          {
               sum = sum + array[i][j];
          }
               if(sum > maxsum)
                    maxsum = sum;
     }
     cout<<"Row No. "<<(Problem is here)<<" has maximum sum: "<<maxsum<<endl;
}

请帮帮我。谢谢! !

你必须记住你的rownumber

#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cstring>
using namespace std;
void calculateMaxRowSum(int array[10][10])
{
    int maxrow = -1;
    int maxsum = 0;
    for (int i = 0; i<10; i++)
    {
        int sum = 0;
        for (int j = 0; j<10; j++)
        {
            sum = sum + array[i][j];
        }
        if (sum > maxsum)
        {
            maxrow = i;
            maxsum = sum;
        }
    }
    cout << "Row No. " << maxrow << " has maximum sum: " << maxsum << endl;
}
int main() {
    int arr[10][10] = { 
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 0
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 1
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 2
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 3
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 4
        { 9,1,1,1,1,1,1,1,1,1}, //Row No. 5 //MAX
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 6
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 7
        { 1,1,1,1,1,1,1,1,1,1}, //Row No. 8
        { 1,1,1,1,1,1,1,1,1,1}  //Row No. 9
    };
    calculateMaxRowSum(arr);
}