函数递归法 1+3+6+···+3n的值
发布网友
发布时间:2024-10-15 21:09
我来回答
共4个回答
热心网友
时间:2024-11-17 15:04
#include <stdio.h>
int sum(int n)
{
if (n==0)
return 1;
else
return sum(n-1) + 3*n;
}
int main()
{
int n;
printf("Please input a number n: ");
scanf("%d", &n);
while (n<0) {
printf("n must be greater than or equal to 0. Please input again: ");
scanf("%d", &n);
}
printf("Result: %d\n", sum(n));
return 0;
}
编译、链接、运行程序,输入与输出如下:
:!gcc -Wall recur.c -o recur
:! ./recur
Please input a number n: -1
n must be greater than or equal to 0. Please input again: 0
Result: 1
:!gcc -Wall recur.c -o recur
:! ./recur
Please input a number n: 4
Result: 31
热心网友
时间:2024-11-17 15:02
#include "stdio.h "
int fun(int a)
{
if(a==0)
return 1;
else
return 3*a+fun(a-1);
}
void main()
{
int a;
scanf("%d",&a);
printf("%d",fun(a));
}
热心网友
时间:2024-11-17 14:59
他的输入是N?
热心网友
时间:2024-11-17 15:04
1+3+6+…+3n=1+3﹙1+2+3…+n﹚=1+3[n/2﹙1+n﹚]=1+3n/2﹙1+n﹚