计算未输出预期答案
Calculation not outputting expected answer
我正试图用公式计算一个数字的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类。。。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- 欧拉项目#8答案是大以获得有效答案
- C++:将控制台输出存储在宏中更好吗
- C++ 中 pow() 函数的输出没有给出准确的答案
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 为什么这两种输出样式给出不同的答案
- 无法在 for 循环中的 pow 函数上输出答案
- 以下代码的输出是什么(答案因差异编译器而异)
- 为什么意外值6295648在输出中带有答案11110001?在这里输入是241和2
- 读取.txt文件中的多行并输出每行的答案
- 你如何得到一个方程,以十进制输出答案
- 使用字符串输出特定答案
- 用c++四舍五入输出答案
- 除法未输出正确答案c++
- 算法输出正确答案,但编程挑战给了我错误的答案
- 计算未输出预期答案
- 简单的计算器问题(不输出答案)
- 程序输出"Heads",与随机生成的答案无关