在泰勒级数展开中动态表示负输出 --> C++

representing negative outputs dynamically in Taylor series expansion --> C++

我正在学习编码,所以请原谅我问这样一个基本问题(总得从某个地方开始,对吧?)我已经编写了以下 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;
        }
}

提前致谢!

您可以替换:

cout << " + " << term;

与:

if (term >= 0)
    cout << " + " << term;
else
    cout << " - " << (-term);

因此,当一个项为负数时,您可以自己打印减号以及您需要的额外 space,然后打印项的正数部分。