首页 > ACM题库 > HDU-杭电 > HDU 1012 u Calculate e[解题报告] C++
2013
11-28

HDU 1012 u Calculate e[解题报告] C++

u Calculate e

问题描述 :

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 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.

样例输出:

n e
- -----------
0 1
1 2
2 2.5
3 2.666666667
4 2.708333333

#include <stdio.h>

int main ( ) {
    int ct, t;
    double sum;
    printf ( "n e\n- " );
    for ( int i = 1; i <= 11; ++i )
        printf ( "-" );
    printf ( "\n" );                                                              
    ct = 0;
    do {
        sum = 1.0, t = 1;
        for ( int i = 1; i <= ct; ++i ) {
            t = t * i;
            sum += ( double )1 / t;
        }
        if ( ct > 2 ) printf ( "%d %.9lf\n", ct, sum );
        else if ( ct == 2 ) printf ( "%d %.1lf\n", ct, sum );
        else printf ( "%d %.0lf\n", ct, sum );
        ct++;
    }while ( ct < 10 );
}