在泰勒级数展开中动态表示负输出-->;C++; 我正在学习代码,所以请原谅我问这样一个基本问题(必须从某个地方开始,对吗?)我写了下面的C++程序,它近似于E^ x级数展开(泰勒级数)。

在泰勒级数展开中动态表示负输出-->;C++; 我正在学习代码,所以请原谅我问这样一个基本问题(必须从某个地方开始,对吗?)我写了下面的C++程序,它近似于E^ x级数展开(泰勒级数)。,c++,c++11,math,taylor-series,C++,C++11,Math,Taylor Series,我的问题是输出。我需要的一个示例输出如下: 样本运行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+-

我的问题是输出。我需要的一个示例输出如下:

样本运行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;
        }
}
#包括
#包括
#包括
使用名称空间std;
整数项,i;
长双x、数字、数字、前置数字、期限、总和;
int main()
{
数量术语;
cout>x;
cout您可以替换:

cout << " + " << term;

cout Hi and welcome!您的问题归结为如何将值
-1
写为
-1
,将值
1
写为
+1
。您应该先相应地减少代码。现在,简单的答案是检查符号并输出
+
x
-
-x
>.您好,谢谢!简化代码很好;我希望最终能够在编写程序时自动完成此操作。我非常感谢您的帮助。编写程序时并不是这样做,而是在查找问题时。此外,这也是stackoverflow规则的一部分,如果您有问题,y你首先把它减少到最小可能的代码。注意。谢谢!如果术语为零,那将打印
-0
if (term >= 0)
    cout << " + " << term;
else
    cout << " - " << (-term);