繁体   English   中英

计算未输出预期答案

[英]Calculation not outputting expected answer

我正在尝试使用公式计算数字的反正切值:

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

我必须将其计算为小数点后20位。 答案应该是0.78539....

这是我编写的代码,包括一些调试语句。 我认为问题出在计算上,但是我看不到它。 有人可以指出我正确的方向吗?

编辑:不能使用atan函数,必须使用来自用户输入的double变量手动计算。

#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<<"Start\n";

   x=x-(pow(x,y)/y);
   y=y+2;
   cout <<  setprecision (20) << x;
   cout<<"=x before loop\n";
   cout<<y;
   cout<<"=y before loop\n";

   for(i=0;i<9;i++)
    {
     x=x+(pow(x,y)/y);
      cout<<x;
      cout<<"=x1 in loop\n";
     y=y+2;
      cout<<y;
      cout<<"=y1 in loop\n";

     x-(pow(x,y)/y);
      cout<<x;
      cout<<"=x2 in loop\n";
     y=y+2; 
      cout<<y;
      cout<<"=y2 in loop\n";
    }
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;
}

我同意@Mystical。 我认为您不会从双精度中获得20位精度。 我认为您需要一个长双精度型(如果系统中存在),或者可能需要实现自己的bignum类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM