背景:
哈哈!我们终于学了递归了,现在大家一定感到非常有意思吧,那个典型的"汉诺塔”问题,一个非常短的程序居然可以完成如此复杂的工作,真是神奇啊!来吧,让我们也动手编写一个递归程序,当然,我们要编写的第一个递归程序不能太复杂了。
功能:求整数 n 到 m 区间的累加和,其中 n<=m。
输入:区间的起始点 n 区间的终止点 m
输出:累加和
要求:必须使用递归算法完成。
#include<stdio.h>
int sum(int n,int m){
if(n==m) return n;
else return m+sum(n,m-1);
}
int main(void){
int a,b;
scanf("%d %d",&a,&b);
printf("The sum from %d to %d is %d.\n",a,b,sum(a,b));
}