所以我的问题主要是指我的输出。我偏离了 atan(x) 的“真实”值,无论它是什么。我知道这一定很简单,我做错了什么?
Please enter the number you would like to apply arctan to as tan^(-1)*(x)
remember, x cannot be greater than 1 or less than negative 1:.5The approx arctan of 0.5000 is 0.4794
The true value arctan of 0.5000 is 0.4636Press any key to continue . . .
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double sum = 0.0, x, denom, term, z;
int n, sign = -1;
char again;
do
{
cout << "Please enter the number you would like to apply arctan to"
<< " as tan^(-1)*(x) \nremember, x cannot be greater than 1 or less than negative 1:";
cin >> x;
cout << endl;
while (x > 1 || x < -1)
{
cout << "Try again, the domain for arctan is ( -1 < x < 1): ";
cin >> x;
cout << endl;
}
if (x > -1 && x < 1)
{
for (n = 0; n < 19; n++)
{
sign = sign * (-1);
z = (n * 2) + 1;
if (n == 0)
denom = 1.0;
else
denom = denom*(2*n)*(2*n+1);
term = sign*pow(x, z)/denom;
sum = sum + term;
}
}
cout << fixed << setprecision(4) << "The approx arctan of " << x << " is " << sum << endl;
cout << "The true value arctan of " << x << " is " << atan(x) << endl << endl;
cout<<"Press Enter";
cin.get();
cin.ignore();
cout << endl;
cout << "Would you like to continue (Y/N)?";
cin >> again;
cout << endl;
}
while (again == 'Y' || again == 'y');
return 0;
}
最佳答案
您的泰勒扩展代码是错误的。
替换denom = denom*(2*n)*(2*n+1);
与 denom = 2*n+1;
它有效
关于C++ "Building a series to solve a function"为什么我的近似值不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022959/