21xrx.com
2025-03-28 13:47:43 Friday
文章检索 我的文章 写文章
C++ 求解二维数组最大值
2023-07-05 05:44:43 深夜i     18     0
C++ 二维数组 最大值 求解

当需要在二维数组中求解最大值时,可以使用C++语言的循环进行计算。下面将介绍一种求解二维数组最大值的方法。

首先,定义一个二维数组并随机填充数值,代码如下:

#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
  const int row = 5;
  const int col = 5;
  int arr[row][col];
  srand(time(NULL));
  for (int i = 0; i < row; i++)
  {
    for (int j = 0; j < col; j++)
    {
      arr[i][j] = rand() % 100;
      cout << arr[i][j] << "\t";
    }
    cout << endl;
  }
  return 0;
}

接下来,我们可以使用两层循环遍历整个二维数组,并通过if语句和一个变量max来计算最大值。代码如下:

#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
  const int row = 5;
  const int col = 5;
  int arr[row][col];
  srand(time(NULL));
  for (int i = 0; i < row; i++)
  {
    for (int j = 0; j < col; j++)
    {
      arr[i][j] = rand() % 100;
      cout << arr[i][j] << "\t";
    }
    cout << endl;
  }
  int max = arr[0][0];
  for (int i = 0; i < row; i++)
  {
    for (int j = 0; j < col; j++)
    {
      if (arr[i][j] > max)
      {
        max = arr[i][j];
      }
    }
  }
  cout << "The max value is: " << max << endl;
  return 0;
}

这样,我们就可以得到一个随机数值的二维数组,并且求出其中的最大值。这个方法的时间复杂度是O(n^2),因为需要遍历整个数组。如果数组规模较大,运行速度会变得很慢。

总的来说,在C++中求解二维数组的最大值并不复杂,只需要使用循环进行计算即可。当然,还有其他的求解方法,比如使用STL中的max_element函数等。不过,掌握最基础的方法仍然是很有必要的。

  
  

评论区