计算未输出预期答案

Calculation not outputting expected answer

本文关键字:答案 输出 未输 计算      更新时间:2023-10-16

我正试图用公式计算一个数字的arctan:

arctan(x) = x - x^3/3 + x^5/5 - x^7/7...

我得把它计算到小数点后20位。答案应该是0.78539....

这是我写的代码,包括一些调试语句。我想问题出在计算上,但我就是看不出来。有人能给我指正确的方向吗?

编辑:无法使用atan函数,必须使用用户输入的双变量手动计算。

#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
 double x;
 int i;
 int j;
 int y=3;
  cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
  cin>>x;
   //Calculate arctan of this number
   cout<<x;
   cout<<"n";
   cout<<y;
   cout<<"n";
   cout<<"Startn";
   x=x-(pow(x,y)/y);
   y=y+2;
   cout <<  setprecision (20) << x;
   cout<<"=x before loopn";
   cout<<y;
   cout<<"=y before loopn";
   for(i=0;i<9;i++)
    {
     x=x+(pow(x,y)/y);
      cout<<x;
      cout<<"=x1 in loopn";
     y=y+2;
      cout<<y;
      cout<<"=y1 in loopn";
     x-(pow(x,y)/y);
      cout<<x;
      cout<<"=x2 in loopn";
     y=y+2; 
      cout<<y;
      cout<<"=y2 in loopn";
    }
return 0;
}

好吧,您的x正在更改!您可能希望使用不同的变量来存储到目前为止计算的值和函数的参数。也就是说,不要期望精确的输出,因为所有这些计算都涉及舍入。

此行:

 x-(pow(x,y)/y);

可能和你的问题有关。

我强烈建议您使用内置的atan函数,它很可能已经针对您的架构进行了很好的优化,并且是大多数C++程序员认可的标准函数。

#include <cmath>
#include <iostream>    
int main()
{
    double d;
    std::cout << "enter number" << std::endl;
    std::cin  >> d;
    std::cout << "atan of: " << d 
              << " is "      << std::atan(d) 
              << std::endl;
    return 0;
}

我同意@Mystic的观点。我认为你不会从一个双精度中得到20位数。我认为你需要一个长的double(如果你的系统中存在的话),或者,也许你需要实现你自己的大num类。。。