简体   繁体   English

C程序使用递归计算X到Y的总数

[英]C Program to calculate sum of numbers X to Y using recursion

I have below code which works fine. 我下面的代码工作正常。

#include<stdio.h>

int calculateSum(int);

int main() {
    int num;
    int result;

    printf("Input number = ");
    scanf("%d", &num);

    result = calculateSum(num);
    printf("\nResult from 1 to %d = %d", num, result);

    return (0);
}

int calculateSum(int num) {
    int res;
    if (num == 1) {
        return (1);
    }
    else {
        res = num + calculateSum(num - 1);
    }
    return (res);
}

Input number = 5 输入数字= 5
Result from 1 to 5 = 15 结果从1到5 = 15

Now I am trying to give the program 2 inputs, from and to numbers. 现在,我尝试为程序提供2个输入,分别为数字。

Example: first input = 5, second = 8 and result should be = 26 (5 + 6 + 7 + 8) 示例:第一个输入= 5,第二个= 8,结果应为= 26(5 + 6 + 7 + 8)

Any ideas of how to go about this? 关于如何解决这个问题的任何想法? failing thus far. 到目前为止失败。

int calculateSum(int fromNum, int toNum) {
    int res;
    if (fromNum == toNum) {
        return (fromNum);
    }
    else {
        res = fromNum + calculateSum((fromNum + 1), toNum);
    }
    return (res);
}

At the moment, you are hard-coding 1 as the terminating point of the recursion. 目前,您正在将1硬编码为递归的终点。

What you need is to be able to use a different value for that, and the following pseudo-code shows how to do it: 您需要的是为此使用不同的值,下面的伪代码显示了如何执行此操作:

def calculateSum(number, limit):
    if number <= limit:
        return limit
    return number + calculateSum(number - 1, limit)

For efficiency, if you break the rules and provide a limit higher than the starting number, you just get back the number. 为了提高效率,如果您违反规则并提供比起始数字更高的限制,则只需取回该数字即可。 You could catch that and return zero but I'll leave that as an exercise if you're interested. 可以捕获并返回零,但是如果您有兴趣,我将其保留为练习。

It should be relatively easy for you to turn that into real code, using your own calculateSum as a baseline. 使用您自己的calculateSum作为基准,将其转换为实际代码应该相对容易。


I should mention that this is a spectacularly bad use case for recursion. 我应该提到,这是递归的一个非常糟糕的用例。 In general, recursion should be used when the solution search space reduces quickly (such as a binary search halving it with each recursive level). 通常,当解决方案搜索空间快速减少时(例如,将每个递归级别的二进制搜索减半),应使用递归。 Unless your environment does tail call optimisation, you're likely to run out of stack space fairly quickly. 除非您的环境没有进行尾部调用优化,否则您可能很快就会耗尽堆栈空间。

Instead of stopping when you reach 1 , stop when you reach from . 相反,当你达到停止1 ,停止当你到达from

int calculateSum(from, to) {
    if (to == from) {
        return from;
    } else {
        return to + calculateSum(from, to-1);
    }
}

change 1 to from: 从1更改为:

int calculateSum(int from,int to) {
    int res;
    if (to== from) {
        return (from);
    }
    else {
        res = to+ calculateSum(from,to - 1);
    }
    return (res);
}

You can use ternary operator. 您可以使用三元运算符。

int calculateSum(int from, int to) {
    return from == to ? from : from + calculateSum(from + 1, to);
}

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

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