u Calculate e - 1517

本文详细介绍了如何通过递归和递推两种方法计算数学常数e的近似值,适用于从n=0到n=9的不同情况。包括了基本输入输出格式说明和代码实现细节。
u Calculate e
Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 19242
Accepted: 11267
Special Judge

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

法1:由于题中就让输出10以内的n,采用递归比较简单:

/***********************************************************************
    Copyright (c) 2015,wangzp
    All rights no reserved.
  
    Name: 《u Calculate e》In PEKING UNIVERSITY ACM
    ID:   PROBLEM 1517
    问题简述: 根据n求e: e=Σ(1/i!),其中 0<=i<=n.
	      采用递归比较简单。
    Date: Sep 25, 2015 
 
***********************************************************************/
#include

double fac(int n)
{
       float f;
	   if(n == 0||n == 1)
	   {
		   f = 1;
	   }
	   else if(n > 1)
	   {
           f = fac(n - 1) * n;
	   }
	   return f;
}

int main(void)
{

	double a,sum=0;
	int i;
	printf("n e\n");
	printf("- -----------\n");
	for(i = 0;i < 10;i++)
	{ 
		a = 1 / fac(i);
		sum = a + sum;
		printf("%d %.9f\n",i,sum);    
	}
	return 0;
}
法2:采用递推也可以,如果n比较大的情况下,采用递推可以节省时间:
/***********************************************************************
    Copyright (c) 2015,wangzp
    All rights no reserved.
  
    Name: 《u Calculate e》In PEKING UNIVERSITY ACM
    ID:   PROBLEM 1517
    问题简述: 根据n求e: e=Σ(1/i!),其中 0<=i<=n.
	          采用递归比较简单,但是耗时,最好采用递推来做。
    Date: Sep 25, 2015 
 
***********************************************************************/
#include

int main(void)
{

	double sum = 1;
	double a,sum_f;
	int i,j;
	printf("n e\n");
	printf("- -----------\n");

	/*i = 0比较简单,单独输出*/
	printf("0 1\n");
	for(i = 1;i < 10;i++)
	{ 
		sum_f = 1;
		for (j = 1;j <= i;j++)
		{
			sum_f *= j;
		}

		a = 1 / sum_f;
		sum = a + sum;
		printf("%d %.9f\n",i,sum);
	}
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值