首页 > 代码库 > poj 1517 & hdu 1012 u Calculate e(简单阶乘)

poj 1517 & hdu 1012 u Calculate e(简单阶乘)

POJ链接 :http://poj.org/problem?id=1517

HDU链接:http://acm.hdu.edu.cn/showproblem.php?pid=1012


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.

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

Greater New York 2000


注意:poj上用G++交WA了,用C++AC,HDU上则不存在此问题。


代码如下:

#include <cstdio>
int Fac(int n)
{
    int s=1;
    for(int i=1; i<=n; i++)
        s*=i;
    return s;
}
int main()
{
    double sum;
    printf("n e\n- -----------\n");
    for(int i = 0; i <= 9; i++)
    {
        sum = 1;
        for(int j = 1; j <= i; j++)
        {
            sum+=1.0/Fac(j);
        }
        if(i <= 1)
            printf("%d %.0lf\n",i,sum);
        else if(i == 2)
            printf("2 2.5\n");
        else if(i > 2)
            printf("%d %.9lf\n",i,sum);
    }
    return 0;
}