HDU 1012 u Calculate e(格式)

u Calculate e
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 53154 Accepted Submission(s): 24348

Problem Description
A simple mathematical formula for e is

where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.

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 Output
n e


0 1
1 2
2 2.5
3 2.666666667
4 2.708333333
这道题目一开始的做法是计算出所有的数据存入double型的数组,然后用%.10g输出(%.10g表示输出结果在10位之内的有效数字,不包含无意义的0),但是由于当n为8时,结果是2.718278770,最后结果中含有无效的0,测试结果也要求输出,于是n等于3之后的结果用%lf输出。

#include<bits/stdc++.h>
using namespace std;
double del(int m)
{
    double mul=1;
    for(int i=1;i<=m;i++)
        mul*=i;
    return 1.0/mul;
}
int main()
{
    double num[10];
    num[0]=1;num[1]=2,num[2]=2.5;
    for(int i=3;i<=9;i++)
    {
        num[i]=del(i)+num[i-1];
    }
    printf("n e\n- -----------\n");
    printf("%d %g\n%d %g\n%d %g\n",0,num[0],1,num[1],2,num[2]);
    for(int i=3;i<=9;i++)
        printf("%d %.9lf\n",i,num[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a17865569022/article/details/81295380