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

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

本文关键字:输出 gt C++ 表示 动态      更新时间:2023-10-16

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

因此,当一个学期是负数时,你可以用你需要的额外空间自己打印减号,然后打印学期的正数部分。