大學生C++教程第九版 習題(4-34) 求階乘

用C++計算e^x的值,公式:e^x=1+x/1!+x^2/2!+x^3/3!+...

#include <iostream>
using namespace std;

double f(int);

int main()
{
	double  n;
	double total = 1;
	double mult=1;
	double x;

	cout << "輸入x:" << endl;
	cin >> x;
	
	cout << "請輸入一個數字n" << endl;
	cin >> n;

	for (int i = 1; i <n; i++)
	{
		mult = mult*x;
		double sign = f(i);
		total = total + mult / sign;

	}

	cout << "自然數e^x的精度爲:" << total << endl;



	

	return 0;
}

double f(int n)
{
	double ftotal = 1;

	for (int i = 1; i <= n; i++)
	{

		ftotal *= i;
	}

	//cout << n << "的階乘爲:" << total << endl;
	return ftotal;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章