简体   繁体   English

矩阵次对角线中的最大值

[英]Maximum value in secondary diagonal of a matrix

This code is supposed to give the maximum value of a secondary diagonal of this matrix 该代码应该给出该矩阵的辅助对角线的最大值

1  2  3  4
4  5  6  8
9 10 11 12

But it's giving an incorrect answer. 但这给出了错误的答案。 There seems to be a slight error in it which I can't pinpoint. 似乎有一个小错误,我无法查明。

#include<iostream>
using namespace std;
int main()
{

  int a[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
  int max = a[0][3];
  cout<<"The matrix is:";

  for(int i = 0; i<4;i++)
  {
    cout<<"\n";
    for(int j=0; j<4; j++)
      cout<<a[i][j]<<" ";
  }

  for(int i = 0; i<4; i++)
  {
    for(int j=0;j<4-i-1;j++)
    {
      if(i+j==3)
      {
        if(max<a[i][j])
        {
          max = a[i][j];
        }
      }
    }
  }

  cout<<"maximum value in second diagonal:"<<max<<endl;

  system("pause");

  return 0;

}

I'd appreciate if someone could help. 如果有人可以提供帮助,我将不胜感激。

Your loop should be 你的循环应该是

for (int i = 1, j = 2; i < 4, j >= 0; i++, j--)
{
  if (max < a[i][j])
  {
     max = a[i][j];
  }
}

It gives the correct value 10 . 它给出正确的值10 No need double loop. 无需双循环。

Your loop has off-by-one error. 您的循环有一次关闭错误。 It should be 它应该是

for(int i = 0; i<4; i++)
{
  for(int j=0;j<4-i;j++)
  {
    if(i+j==3)
    {
      if(max<a[i][j])
      {
        max = a[i][j];
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM