c++ 自定义sin出现了一些问题

2025-03-10 13:06:06
推荐回答(1个)
回答1:

你的代码有一些地方存在问题。

1.这里x在后面的公式里不是弧度,而是double的值:

所以你这里的x=x*3.1415926/180是不需要的,不要在这里做转换。

2.这里循环体里的问题:

你a=a*x*x?是什么意思?你默认通项里面的x的2n+1次方是x的3次方吗?这里有问题应该写循环。

3.同2.这里c你当做2n+1的阶乘,也应该写循环。

4.代码的命名方式太业余了。。。我看了半天才看懂你要写什么。

5.我简单的调试了下代码,你可以参考下我的进行修改。我测试用例是x=5.0输出结果

#include 
#include "math.h"
int main () 
{
        double x = 5.0;
    double dResult = 0.0;
     
    for (int n = 0; n < 100; n ++)
    {
        int iPrat_One = 1;
        double dPart_Two = 1.0;
        double dPart_Three = 1.0;
 
        if (n == 0)
        {
            iPrat_One = 1;
            dPart_Two = x;
            dPart_Three = 1.0;
        }
        else
        {
            for (int i = 0; i < n; i++)
            {
                iPrat_One *= -1;//-1的n次方
            }
            for (int i = 0; i < 2*n+1; i++)
            {
                dPart_Two *= x;
                dPart_Three *= (double)(i+1);
            }
        }
 
        printf("\n%f",iPrat_One*dPart_Two/dPart_Three);
        dResult += iPrat_One*dPart_Two/dPart_Three;
    }
    printf("\n*******************************");
    printf("\n%f",dResult);
 
    printf("\n%f",std::sin(5.0));
}

PS毕业一段时间不接触高数快忘完了。。看不出通项的敛散性,我只能调试了下发现是收敛到0的,所以我只让n做了100次循环,不放心可以填个大点的数。

配个图。。iPart_One,dPart_Two和dPart_Three代表图中3个部分.