我正在学习编码,所以请原谅我提出这样一个基本问题(必须从某个地方开始,对吗?)我编写了以下 C++ 程序,它近似于 e^x 级数展开(泰勒级数)。
我遇到的问题是输出。我需要的示例输出之一如下:
样品运行 5:
该程序使用 n 项级数展开逼近 e^x。输入要在 e^x-> 8 的近似值中使用的项数 输入指数(x)-> -0.25
e^-0.25000 = 1.00000 - 0.25000 + 0.03125 - 0.00260 + 0.00016 - 0.00001 + 0.00000 - 0.00000 = 0.77880
但我的代码改为创建以下输出:
e^-0.25000 = 1.00000 + -0.25000 + 0.03125 + -0.00260 + 0.00016 + -0.00001 + 0.00000 + -0.00000 = 0.77880
本质上,我不确定如何动态地表示这些负值,以匹配所需的输出。目前,它们在我的代码中都是用“+”字符串文字表示的,在重复的递归术语之间。
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int numTerms, i;
long double x, numer, denom, prevDenom, term, sum;
int main ()
{
cout << "This program approximates e^x using an n-term series expansion." << endl;
cout << "Enter the number of terms to be used in the approximation of e^x-> ";
cin >> numTerms;
cout << "Enter the exponent(x)-> ";
cin >> x;
cout << endl;
if (numTerms <= 0)
cout << numer << " is an invalid number of terms." << endl;
else if (numTerms == 1)
{
sum = 1.00000;
cout << "e^" << fixed << setprecision(5) << x << " = " << sum << " = " << sum << endl;
}
else
{
cout << "e^" << fixed << setprecision(5) << x <<" = " << 1.00000;
sum += 1.00000;
prevDenom = 1;
for (i = 1; i < numTerms; i++)
{
numer = pow(x,(i));
denom = (prevDenom) * (i);
term = numer / denom;
sum += term;
prevDenom = denom;
cout << " + " << term;
}
cout << " = " << fixed << setprecision(5) << sum << endl;
}
}
提前致谢!