计算并输出e
公式:e=1+ 1/1!+1/2!+...+1/n!输入:一个整数n。
输出:公式计算的结果e的值
#include <stdio.h> int main() { unsigned long product; int i,j,n; double k=0; printf("输入一个数:"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1,product=1;j<i;j++) product*=j; k+=1.0/product; } printf("%lf",k); return 0; }
#include <stdio.h> double foo( unsigned n ) { double result = 1; double tmp = 1; for( unsigned i=0; i!=n; ++i ) { tmp /= i+1; result += tmp; } return result; } //#include <assert.h> int main( void ) { //assert( foo(0) == 1 ); //assert( foo(1) == 1 + 1/1 ); //assert( foo(2) == 1 + 1/1 + 1/2. ); //assert( foo(3) == 1 + 1/1 + 1/2. + 1/6. ); unsigned n; scanf( "%u", &n ); printf( "%f\n", foo(n) ); }
[此贴子已经被作者于2022-10-31 14:49编辑过]