编写递归函数求1+2+3+...+N的值

这是一道简单的VB编程题
2024-10-30 06:01:21
推荐回答(4个)
回答1:

#include
int sum( int n );
int main()
{
int n;
scanf("%d", &n);
printf ("%d\n", sum(n));
return 0;
}
int sum( int n ){
if(n==0)
return 0;
else
return n+sum(n-1);
}

回答2:

#include

int sum(int i,int n);

int main()
{

int i=1;
int n;
scanf("%d", &n);
printf ("%d\n", sum(i,n));

return 0;
}

int sum(int i,int n)
{
int result;
if(i {
result=i+sum(i+1,n);
return result;
}
else
return n;
}

回答3:

for i=1 to n
sum=sum+i
next i
print sum

回答4:

int Sum(int N)
{
if(N=1)
return N;
else return Sum(N-1)+N;
}