繁体   English   中英

数组递归 无法获得正确的值来返回

[英]Recursion with an Array; can't get the right value to return

找到解决方案-不到5分钟,谢谢大家!

澄清:我数组的内容是值0-29。 所以array [0] [0] = 0,而array [29] [0] = 29 ---它们只是测试值。 另外,我已经发布了一个潜在的解决方案,请尝试一下。

递归解决方案:不起作用! 说明:一个整数,时间,被传递给该函数。 然后用于结束FOR语句( counter<time )。 IF部分( time == 0 )提供了一种基本情况,递归应该终止,返回0。ELSE部分是递归调用发生的地方:total是在头文件中定义的私有变量。 在其他地方的构造函数中将其初始化为0。 该函数递归地调用自身,一次又一次地将productsAndSales[time-1][0]相加,直到基本调用为止。 然后将总数返回,并在以后打印出来。 好吧,那是我一直希望的。

我想象会发生的事情是,我将把该数组的这一列中的所有值加起来,然后该值将被返回并打印出来。 相反,如果if返回0。如果我将IF部分设置为“ return 1”,我注意到无论返回值是多少,它都会返回2的幂。 EG:时间= 3,则返回2 * 2 +1。如果时间= 5,则返回2 * 2 * 2 * 2 + 1。

我不明白为什么它没有返回我期望的值。 我想到的一件事是,我试图在return部分中使用私有变量total以及递归调用……也许这是不行吗?

int CompanySales::calcTotals( int time )
{
  cout << setw( 4 );
  if ( time == 0 )
   {
    return 0;
   }
  else
   {
    return total += calcTotals( productsAndSales[ time-1 ][ 0 ]);
   }
}

迭代解决方案:有效! 说明:一个整数,时间,被传递给该函数。 然后用于结束FOR语句( counter<time )。 FOR语句遍历数组,将一列中的所有值加在一起。 然后返回该值(并打印出程序的其他位置)。 完美运作。

int CompanySales::calcTotals( int time )
{
 int total = 0;
 cout << setw( 4 );

 for ( int counter = 0; counter < time; counter++ )
 {
  total += productsAndSales[counter][0];
 }
 return total0;
}

不要使用全局total ,而应将其作为参数。

int totals = calcTotals(time-1, 0); // Call it starting at the end, 
                                    // so we don't have to pass along the `time`


int CompanySales::calcTotals( int counter, int total )
{
  if ( counter == 0 ) {
    return total;
  }
  else {
    return calcTotals(counter - 1, total + productsAndSales[counter][ 0 ]);
  }
}

现在它也是尾递归的。

好吧,在您的递归函数中,您希望时间作为函数的参数,但是当您进行递归调用时,它传递的是productAndSales数组的值,而不是我期望的(time-1)。

因此,假设productAndSales数组的内容不包含零,则永远不会发生time == 0终止检查

传递了错误的论点:

total += calcTotals( productsAndSales[ time-1 ][ 0 ]);

应该:

total +=  productsAndSales[ time ][ 0 ]  + calcTotals(time - 1);

应该

return total += productsAndSales[time - 1][0] + calcTotals(time - 1);

这将产生与迭代函数相同的结果。

int CompanySales::calcTotals( int time )
{
  cout << setw( 4 );
  if ( time == 0 ){
    return 0;
  }
  else{
    return productsAndSales[time-1][ 0 ] + calcTotals( time - 1 );
  }
}

无处在你的递归解决方案,你实际上添加productsAndSales值-你在这些值传递的时间参数的calcTotals()函数。

因此,如果total从零开始,您只是简单地多次调用此函数,并且从不添加零以外的任何东西。

这不应该是

int CompanySales::calcTotals( int time )
{
  int total = 0;
  cout << setw( 4 );
  if ( time == 0 )
   {
    return 0;
   }
  else
   {
    return total += productsAndSales[ time ][ 0 ] + calcTotals( time - 1);
   }
}

暂无
暂无

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

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