使用结构和递归查找整数数组中的最大数字

Use struct and recursion to find the largest number in an integer array

本文关键字:数字 数组 整数 结构 递归 查找      更新时间:2023-10-16

我需要使用递归来查找整数数组中的最大数字。另外,我需要获取最大数字的值和索引。我使用了"结构",但它给了我一些奇怪的数字,我不知道为什么。

这是我的结构:

struct maxNumber
{
    int index;
    int value;
};

这是我的find_largest函数:

maxNumber Numbers::find_largest()
 {
      maxNumber max;
      int current ;//keep track of the current counter
      if(size == 1)
      {
          max.value = numArray[0];
          max.index = 0;
          return max;
      }
      if(current < size && size != 0)  //loop through all numbers in the array
      {
          if(numArray[current] >= max.value)
           {
            max.value = numArray[current];
            max.index = current;
           }
       current++;
       find_largest();
       }

       return max;
 }

然后,在主函数中,我只是这样做:

int result = num.find_largest().value;
cout << "The largest number is " << result << endl; 

但是,它给了我一个非常大的数字。需要一些帮助来找出问题所在。

您的主要问题是current具有本地存储,因此在每次调用findLargest时都会重新分配。 将声明更改为此声明

static int current = 0;

如果在类定义中的其他地方正确定义了sizenumArray,它应该可以工作。

但是同样的事情在max上更微妙地发生,它也应该静态声明。

刚刚修复了这个问题。问题正如@stvcisco所说:我没有在函数中传递参数,所以它只是一次又一次地调用函数。这是固定代码。

 maxNumber Numbers::find_largest(maxNumber max, int size)
{
    if(size == 1)
    {
        max.value = numArray[0];
        max.index = 0;
    }
    if( size > 1)  //loop through all numbers in the array
    {
        if(numArray[size-1] >= max.value)
        {
            max.value = numArray[size-1];
            max.index = size-1;
            return max = find_largest(max, size-1);
        }
        //return max = find_largest(max, size-1);
        else
        {
            size--;
            find_largest(max,size);
        }
    }

    return max;
}