简体   繁体   English

C++ 使用递归问题的数组最大值

[英]C++ max of an array using recursion issue

I have this program that finds the largest integer in an array using recursion, but it keeps returning the last number entered no matter what the value instead of the largest number.我有这个程序,它使用递归在数组中找到最大的 integer,但无论值是什么,它都会返回最后输入的数字,而不是最大的数字。 How do i fix this?我该如何解决?

#include <iostream>

using namespace std;

int maximum(int digits[], int size, int largest, int i);

void main()
{
  const int size = 3;
  int digits[size];
  int n = 0, x = 0;

  for(int a = 0; a < size; a++)
  {
      cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
      cin >> digits[n];
  }

  cout << "\nThe largest digit is, " << maximum(digits, size, 0, 0) << ", thank you!\n";
  cout << endl;
}


int maximum(int digits[], int size, int largest, int i)
{
  if ( i < size )
  {
      if ( largest < digits[i])
          largest = digits[i];

      maximum( digits, size, largest, i + 1);
  }
  return largest;
}

It should be return maximum( digits, size, largest, i + 1); 它应该是return maximum( digits, size, largest, i + 1);

Live example . 现场例子

First use the index variable properly in main() 首先在main()正确使用index变量

  for(int a = 0; a < size; a++)
  {
      cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
      cin >> digits[a];//-->Use the index varible correctly.
  }

int maximum(int digits[], int size, int largest, int i)
{
  if(i==size-1)
    return digits[i]; //The base case is specified here.
  if ( i < size )
  {
      int temp= maximum( digits, size, largest, i + 1);
      if ( digits[i] < temp)
          largest =temp;
      else
         largest=digits[i];

  }
  return largest;
}

Please check out the changes. 请检查更改。 Carefully read the code. 仔细阅读代码。 You will understand your mistakes. 您将了解您的错误。

When designing recursion think of few things first- 在设计递归时,首先要考虑的几件事-

  • The base condition. 基本条件。 (This stops the recursion). (这将停止递归)。

  • The recursive step. 递归步骤。 (Where you will calculate something based on previous calculation) (您将根据先前的计算来计算内容)

  • Combine step- You have to combine them (value at this stage and value got from recusive step) to get the correct answer. 合并步骤-您必须将它们合并(此阶段的值和从追溯步骤获得的值)才能获得正确的答案。 This step is not required in some cases. 在某些情况下,不需要此步骤。

int biggestOne(int integerArray[], int lengthOfArray, int max)
{
    if (lengthOfArray==0) return max;
    if (max < integerArray[lengthOfArray-1]) max = integerArray[lengthOfArray-1];
    return biggestOne(integerArray,lengthOfArray-1,max); 
}

int main()
{
    int array[] = {7,2,9,10,1};
    int arrSize = sizeof(array)/sizeof(array[0]); //returns length of the array

    cout <<"Biggest number in the array: " << biggestOne(array,arrSize,0) << endl;
    return 0;
}

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

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