使用递归计算数组中只有正元素的总和

数组充满了随机元素(负数和正数)。 现在我想计算只有正元素的总和。

迭代没有问题,但在递归版本中我只能获得负面和正面的总和。

如何在递归版本中“检查”它只能总结正面元素?

迭代版本:

public int IterSomPosElem(int[] tabel, int n) { n = 0; for (int i = 0; i = 0) { n += tabel[i]; } } return n; } 

目前的递归版本(总结所有元素而不仅仅是积极的):

 public int RecuSomPosElem(int[] tabel, int n) { if(n == 1) return tabel[0]; //stopCriterium else { return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1)); // how to check, so it only sums up the postive elements and "ignores" the negative elements. } } 

这是家庭作业吗? 为什么需要使用递归函数执行此操作?

在现实世界中,它将是一些简单的LINQ

 int positiveSum = tabel.Where(i => i > 0).Sum(); 

怎么样

 int foo[] = new [] {1, -9, 10, 8, -16, ...}; int sumOfPostiveInts = foo.Sum(x => x < 0 ? 0 : x); or...foo.Where(x => x > 0).Sum(); 

就像是?

 public int RecuSomPosElem(int[] tabel, int n) { if(n == 1) return tabel[0]; //stopCriterium else { var valueToSum = tabel[n - 1] > 0 ? tabel[n - 1] : 0; return (valueToSum + RecuSomPosElem(tabel, n - 1)); } } 
 public int RecuSomPosElem(int[] tabel, int n) { if(n == 1) return tabel[0]; //stopCriterium else { if (tabel[n - 1] > 0) return (tabel[n - 1] + RecuSomPosElem(tabel, n - 1)); else return RecuSomPosElem(tabel, n - 1)); } } 

你真是太近了! 使用您的算法,但只需添加一个检查以查看表中的当前值是否为负数。 如果为负,则转到下一个数组项:

  private static int RecuSomPosElem(int[] tabel, int n) { int i = n - 1; while (tabel[i] < 0 && i > 0) i--; if (i == 0) { return 0; //stopCriterium } else { return (tabel[i] + RecuSomPosElem(tabel, i)); } }