注册 登录
编程论坛 C++教室

这个球arctan()的函数怎么错了呢?

slash5999 发布于 2013-05-04 12:08, 1710 次点击
arctanx=x-x^3/3+x^5/5-x^7/7+.....
直到级数某项绝对值不大于1e-15为止

我的代码如下
#include <iostream>
#include <cmath>
using namespace std;
double power(double x,int n)
{double val=1.0;
while(n--)
val*=x;
return val;
}


double arctan(double x)
{
    long int p=1;
    double a=x;
    double sum=0;

    long int t=0;
    while(abs(a)>=1e-15)
    {

        a=power(x,p)/p;
        sum+=a*(power(-1,t));
        t++;
        p+=2;
    }
    return sum;
}


int main()
{
    cout<<arctan(1.0);
    return 0;
}


按理说应该输出0.785
而我的程序输出的是:0.6666
请问我的程序在哪里出了问题?
3 回复
#2
rjsp2013-05-04 12:22
看了一下你的代码,除了效率极低外,倒也没什么逻辑错误。
另外,“直到级数某项绝对值不大于1e-15为止”,其中x为1.0是,也就是某项为 1/1e15 时,你得算到 五百万亿 次才结束。我不知道你运行了多久就有了“而我的程序输出的是:0.6666”?
#3
rjsp2013-05-04 12:25
哦,还有一个最严重的问题,既然需要某项小于 1/1e15,那么那时你的 p(类型是long int) 已经早就溢出了
#4
slash59992013-05-05 15:38
恩,我懂了,谢谢!
1