C语言编程,求1!+2!+3!+......+20!,用到函数

2024-11-27 02:31:50
推荐回答(5个)
回答1:

你好!

请参考:
#include

double fac(int n)
{
return n > 1 ? n * fac(n-1) : 1;
}

double _facsum(double x, double y)
{
return y > 1 ? _facsum((x+1)*(y-1), y-1) : x;
}

double facsum(double x)
{
return _facsum(x, x);
}

int main()
{
printf("%.f\n", facsum(20)); // 1! + 2! + 3!+...+20!
return 0;
}
#include

double fac(int n)
{
return n > 1 ? n * fac(n-1) : 1;
}

double _facsum(double x, double y)
{
return y > 1 ? _facsum((x+1)*(y-1), y-1) : x;
}

double facsum(double x)
{
return _facsum(x, x);
}

int main()
{
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout << facsum(20); // 1! + 2! + 3!+...+20!
return 0;
}
迭代版:
#include

int main()
{
int i, j;
double k, sum;
for(sum = 0, i = 1; i <= 20; ++i) { // 1! + 2! + 3!+...+20!
for(k = 1, j = i; j >= 1; --j)
k *= j;
sum += k;
}
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout << sum;
return 0;
}

回答2:

代码如下:
//***************************************************************************************
//***************************************************************************************
#include
int main()
{
int i=0;
long temp=1;
long sum=0;
for(i=1;i<=20;i++)
{
temp*=i;
sum+=temp;
}
printf("sum=%ld\n",sum);
return 0;
}
//***************************************************************************************
//***************************************************************************************
_________________
cl之后,执行:
_________________

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

baidu.c
Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

/out:baidu.exe
baidu.obj
sum=268040729

请按 ENTER 或其它命令继续
_________________
to 楼上:
你的for里边的sum1每次重新从1开始算,很浪费的,直接用上一次的结果就行.

回答3:

#include
long foo(int n)
{
if (1 == n)
return 1;
return n * foo(n - 1);
}

int main(void)
{
int i;
long sum = 0;
for (i = 1; i <= 3; i++)
{
sum += foo(i);
}
printf("总和是%ld\n", sum);

return 0;
}

回答4:

unsigned long long f(int n)
{
unsigned long long sum=0,t=1;
for(int i=1;i<=n;t*=i++,sum+=t);
return sum;
}
main()
{
printf("%lld", f(20) );
}

回答5:

long long f(int n)
{
if(n<=1) return 1;

long long r=1;
for(int i=2;i<=n;i++)
r*= i;
return r;
}

void main()
{
long long sum =0;
for(int i=1;i<=20;i++)
sum += f(n);
}