u Calculate e

#include <iostream>
#include <iomanip>
#include <cassert>
using namespace std;

int factorial(int i)
{
    if(i==0 || i==1)
    {
        return 1;
    }
    else
    {
        int product = 1;
        for(int j=1; j<=i; j++)
        {
            product = product*j;
        }
        return product;
    }
}
int main()
{
    long double sum = 0;
    cout << "n e" << endl;
    cout << "- -----------" << endl;
    for(int n=0; n<10; n++)
    {
        sum = 0;
        for(int i=0; i<=n; i++)
        {
            assert(factorial(i) != 0);
            sum += 1.0/factorial(i);  //1.0 other than 1
        }
        cout.precision(10);
        if (n > 2)
        {
            cout.setf(ios::showpoint);//强制输出相加产生的末尾的0
        }
        cout << n << ' ' << sum;

        cout << endl;

    }
    return 0;
}

以上是我写的,下面是转来的:

#include<stdio.h>
int main()
{
    int x=2,i=3;
    double sum = 2.5;
    printf("n e\n");
    printf("- -----------\n0 1\n1 2\n2 2.5\n");
    for(i = 3; i != 10; i++){
        x*=i;
        sum+=1.0/(double)x;
        printf("%d %.9f\n",i,sum);
    }
}

posted @ 2011-03-20 22:36  SunnyDay2015  阅读(309)  评论(0编辑  收藏  举报