我需要计算 arctan(x) 并且结果显示"nan",我的代码有什么问题?



所以im得到的值是"nan";我怀疑我的while陈述有问题。

#include <iostream>
#include <math.h>
using namespace std;
int main()
{   int n=1,c=0;
float x;
double sum=0, old_sum, diff=1000000,eps;
cin>>x>>eps;
while(abs(diff)>=eps){
old_sum=sum;
sum=sum+double(pow(x,n)/n)*double(pow(-1,c));
c++;
n+=2;
diff=sum-old_sum;
}
cout<<sum<<"n";
cout<<atan(x);
return 0;
}

我对x的输入是21,对eps的输入是0.01,我得到的是nan和atan函数的正确值。

您的代码中存在以下几个问题:

  • 您没有考虑到该公式仅对abs(x) <= 1有效。这可以通过一个小数学技巧来解决
  • 你没有检查公式是否有效收敛。这可以通过测试n的值来完成
  • 您正在重复使用pow(.)函数。这没用。这不会带来坏结果,但效率很低
#include <iostream>
#include <cmath>
int main() {
int n = 3;
int n_max = 200;
double x;
double eps;
std::cin >> x >> eps;
double x_sav = x;
x = x / (1.0 + sqrt(1+x*x));        // the trick to handle abs(x) > 1
int sign = -1;
double term = x;
double powerx = x;
double sum = x;
double x2 = x*x;
while (std::abs(term) > eps && n <= n_max) {
powerx *= x2;
term = powerx / n;
sum += term * sign;
n += 2;
sign = -sign;
}
if (n > n_max) {
std::cout << "The series did not convergen";
return 1;
}
sum *= 2.0;     // following of the trick
std::cout << sum << "n";
std::cout << atan(x_sav) << "n";
return 0;
}

最新更新