用递归求和 哪位高手指点指点吧!!
#include<stdio.h>main()
{long n,m,a,b,p;
scanf("%d %d",&n,&m);
p=sum(n,m);
printf("The sum from %d to %d is %d\n",n,m,p);
}
sum(long n,long m)
{
if(n==m) return(n);
else
return(n+sum(n-1,m));
}
错哪了呢?
----------------解决方案--------------------------------------------------------
#include <stdio.h>
long int sum(long,long);
int main(void)
{
long int n,m;
scanf("%d %d",&n,&m);
printf("The sum from %d to %d is %d\n",n,m,sum(n,m));
return 0;
}
long int sum(long n,long m)
{
if(n==m)
return m;
else
return m+sum(n,m-1);
}
----------------解决方案--------------------------------------------------------
高手,还是过不去呀
----------------解决方案--------------------------------------------------------
过不去,你至少把错误说一下吧
----------------解决方案--------------------------------------------------------
不知道程序具体要实现什么目的,我的理解就是求两个输入数字的和,根据我自己的理解,把程序改了下....在VC下通过了:
#include <stdio.h>
long int sum(long,long);
int main(void)
{
long int n,m;
scanf("%d %d",&n,&m);
printf("The sum from %d to %d is %d\n",n,m,sum(n,m));
return 0;
}
long int sum(long n,long m)
{
long temp;
if(n<m){temp=n;n=m;m=temp;}
if(n==m)
return 2*m;
else
return 1+sum(n-1,m);
}
----------------解决方案--------------------------------------------------------
用用这个程序
#include<stdio.h>void main()
{long n,m,a,b,p;
clrscr();
scanf("%ld %ld",&n,&m);
p=sum(n,m);
printf("The sum from %ld to %ld is %ld\n",n,m,p);
}
sum(long n,long m)
{
if(n==m)
return(m);
else
return(m+sum(n,m-1));
}
----------------解决方案--------------------------------------------------------
LZ写的没错,只是少了函数声明, 还要注意的是 你输入的两个数,必须是大在前,小的在后, 因为你的递归中 就是那样计算的
----------------解决方案--------------------------------------------------------