u Calculate e
| Time Limit: 1000MS | Memory Limit: 10000K | |||
| Total Submissions: 19242 | Accepted: 11267 | Special Judge | ||
Description
A simple mathematical formula for e is
e=Σ0<=i<=n1/i!
where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.
where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.
Input
No input
Output
Output the approximations of e generated by the above formula for the values of n from 0 to 9. The beginning of your output should appear similar to
that shown below.
Sample Input
no input
Sample Output
n e
- -----------
0 1
1 2
2 2.5
3 2.666666667
4 2.708333333
...
Source
法1:由于题中就让输出10以内的n,采用递归比较简单:
/***********************************************************************
Copyright (c) 2015,wangzp
All rights no reserved.
Name: 《u Calculate e》In PEKING UNIVERSITY ACM
ID: PROBLEM 1517
问题简述: 根据n求e: e=Σ(1/i!),其中 0<=i<=n.
采用递归比较简单。
Date: Sep 25, 2015
***********************************************************************/
#include
double fac(int n)
{
float f;
if(n == 0||n == 1)
{
f = 1;
}
else if(n > 1)
{
f = fac(n - 1) * n;
}
return f;
}
int main(void)
{
double a,sum=0;
int i;
printf("n e\n");
printf("- -----------\n");
for(i = 0;i < 10;i++)
{
a = 1 / fac(i);
sum = a + sum;
printf("%d %.9f\n",i,sum);
}
return 0;
}
法2:采用递推也可以,如果n比较大的情况下,采用递推可以节省时间:
/***********************************************************************
Copyright (c) 2015,wangzp
All rights no reserved.
Name: 《u Calculate e》In PEKING UNIVERSITY ACM
ID: PROBLEM 1517
问题简述: 根据n求e: e=Σ(1/i!),其中 0<=i<=n.
采用递归比较简单,但是耗时,最好采用递推来做。
Date: Sep 25, 2015
***********************************************************************/
#include
int main(void)
{
double sum = 1;
double a,sum_f;
int i,j;
printf("n e\n");
printf("- -----------\n");
/*i = 0比较简单,单独输出*/
printf("0 1\n");
for(i = 1;i < 10;i++)
{
sum_f = 1;
for (j = 1;j <= i;j++)
{
sum_f *= j;
}
a = 1 / sum_f;
sum = a + sum;
printf("%d %.9f\n",i,sum);
}
return 0;
}

本文详细介绍了如何通过递归和递推两种方法计算数学常数e的近似值,适用于从n=0到n=9的不同情况。包括了基本输入输出格式说明和代码实现细节。
294

被折叠的 条评论
为什么被折叠?



