在泰勒级数展开中动态表示负输出 --> 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);
因此,当一个学期是负数时,你可以用你需要的额外空间自己打印减号,然后打印学期的正数部分。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词