21: 计算e

21 计算e

作者: Turbo时间限制: 1S章节: 循环

问题描述 :
利用公式e=1+ 1/1! + 1/2! + 1/3! + ... + 1/n!,编程计算e的近似值,直到最后一项的绝对值小于threshold(该项不包括在结果内),输出e的值并统计累加的项数。

输入说明 :
输入一个实数threshold,表示累加的阈值,数列中最后一项的值大于等于该阈值。Threshold最小可为1e-10。

输出说明 :
输出一个实数表示e的值,保留6位小数,并输出一个整数,表示累加的项数。两个数字之间用一个空格分隔,在行首和行尾没有多余的空格。

输入范例 :
0.00001
输出范例 :
2.718279 9
代码:

#include <stdio.h>
#include <math.h>
int main()
{
	double threshold;
	double e = 1.0, n = 1.0, m = 1.0;
	scanf("%lf", &threshold);
	if (threshold > 1.0)
	{
		printf("0.000000 0");
	}
	else
	{
		while (fabs(1 / m) >= threshold)
		{
			m = 1.0;
			for (double i = 1.0; i <= n; i++)
			{
				m *= i;
			}
			if (fabs(1 / m) >= threshold)
			{
				e += fabs(1 / m);
				n++;
			}
		}
printf("%.6lf %d", e, (int)n);
 
	}
        return 0;
}
Yesterday is history,tomorrow ismystery,but today is a gift!That why it is called Present!
原文地址:https://www.cnblogs.com/VictorierJwr/p/12248816.html