使用递归求和 [英] Using recursion to sum numbers

查看:34
本文介绍了使用递归求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在研究递归的概念,我想我会尝试一个简单的例子.在下面的代码中,我试图取数字:1、2、3、4、5,并使用递归将它们加在一起.我预计结果为 15,但我的代码返回 16.

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, and add them together using recursion. I expected the result to be 15, but my code is returning 16.

我做错了什么?

    static void Main(string[] args)
    {
        
        Console.WriteLine(Sum(5));
        Console.Read();
    }


    static int Sum(int value)
    {
        if (value > 0)
        {
          return value + Sum(value - 1);
        }
        else
        {
            return 1;
        }
    }

推荐答案

您将在 else 子句中返回 1.你应该返回 0:

You're returning 1 in the else clause. You should be returning 0:

else
{
    return 0;
}

如果值不大于零,你为什么要首先返回一个?

If the value is not greater than zero, why would you return one in the first place?

这篇关于使用递归求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆