繁体   English   中英

递归,计算正整数的总和

[英]recursion, computing sum of positive integers

所以,我的重点是打印出正数的总和,我把它添加和打印得很好,唯一的问题是它也添加了负数。

关于为什么会这样的任何想法? 我只是想让它加上正数。

public static double computeSumPositive(double[]numbers, int count) 
{
double total=0;
{
if(count>0) 
        {
            total = numbers[count-1] + computeSumPositive(numbers, count -1); 
            return total;
        }
        else 
            return total;
        } 
}

您需要检查要添加的值。 就像是:

    public static double computeSumPositive( double[] numbers, int count )
    {
        double total = 0;
        {
            if( count > 0 )
            {
                double val = (numbers[count - 1] > 0)?numbers[count - 1]:0;
                total = val + computeSumPositive( numbers, count - 1 );
                return total;
            }
            else
                return total;
        }
    }

因为您没有检查所讨论的数字是否为负数,所以如果我正确理解您想忽略numbers数组中的所有负数,如下所示:

public static double computeSumPositive(double[] numbers, int count) {
    double total = 0;
    if (count > 0) {
        if (numbers[count - 1] < 0) {
            total = numbers[count - 1] + computeSumPositive(numbers, count - 1);
        } else {
            total = computeSumPositive(numbers, count - 1);
        }
    }
    return total;
}

您也不需要在每次代码循环时都返回if jus 返回值。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int sumPosRecur(int array[], int len) 
{
    if(array)
    {
        /* len greater than 0 */
        if(len > 0)
        {
            if(len == 1)
            {
                /* return a positive int */
                if(array[0] > 0)
                {
                    return array[0];
                }

                else return 0;/* return 0 if negative int */
            }       

            if(len > 1)
            {
                if(array[len-1] > 0)
                {
                    return array[len - 1] + sumPosRecur(array, len - 1);/* return sum of all positive ints by recursively calling */
                }

                else return sumPosRecur(array, len - 1);/* go next round of recursively call if isn't positive int */
            }
        }/* if(len > 0) */

        /* return 0 */
        if (len == 0)
        {
            return 0;
        }

        /* return -1 */
        if (len < 0)
        {
            return -1;
        }

    }/* if(array) */

    /* return -2 */
    else return -2;
}

int main() 
{
    int array[] = {1, 2, 3, 4, 5};
    int len = 5;
    int result;

    result = sumPosRecur(array, len);
    printf("%d\n", result);
    return 0;
}

暂无
暂无

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

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