简体   繁体   English

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

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

I'm required to use recursion to find the largest number in an integer array. 我需要使用递归来查找整数数组中的最大数字。 Also, I need to get both the value and index of the largest number. 另外,我需要同时获取最大数量的值和索引。 I used "struct" but it gave me some weird number and I cannot figure out why. 我使用“结构”,但它给了我一些奇怪的数字,我不知道为什么。

Here's my struct: 这是我的结构:

struct maxNumber
{
    int index;
    int value;
};

Here's my find_largest function: 这是我的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;
 }

Then, in the main function, I just did this: 然后,在主函数中,我只是这样做了:

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

However, it gives me a very large number. 但是,它给了我很多。 Need some help to figure out what's wrong. 需要一些帮助来找出问题所在。

Your main problem is that current has local storage and thus is reallocated on every call to findLargest . 您的主要问题是, current具有本地存储,因此在每次调用findLargest时都会对其进行重新分配。 Change the declaration to this 将声明更改为此

static int current = 0;

and it should work, if size and numArray are defined properly elsewhere in the class definition. 如果在类定义的其他位置正确定义了sizenumArray ,它应该可以工作。

But the same thing is happening more subtly with max , and it should be declared statically as well. 但是max更巧妙地发生同一件事,因此也应该静态声明它。

Just got this fixed. 刚解决这个问题。 The problem is as what @stvcisco said: I didn't pass the parameters in the function, so it just call the function within itself again and again. 问题就如@stvcisco所说的:我没有在函数中传递参数,因此它只是一次又一次地调用函数。 Here's the fixed code. 这是固定代码。

 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;
}

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

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