这个用static怎么做啊
编程计算1+(1+2)+(1+2+3)+…+(1+2+3+…+n)的前n项的和。要求每一项的计算由函数完成,函数中用static定义局部变量来完成计算。在主函数中输入n的值,输出计算结果。 unsigned long long fun(unsigned long long n){
static unsigned long longsum=0;
sum+=(1+n)*n/2;
return sum;
}
int main()
{
unsigned long longn=0,sum=0;
scanf("%llu",&n);
for(int i=1;i<=n;i++)sum=fun(i);
printf("%llu",sum);
return 0;
} jhq999 发表于 2022-5-30 16:22
#include <stdio.h>
unsigned long long foo(int n) {
static unsigned long long res;
if (!n) return res;
for (int i = 1; i <= n; ++i) res += i;
return foo(n - 1);
}
int main()
{
printf("%lld", foo(4));
return 0;
}20
页:
[1]