代码块不能运行代码即使代码没有错误

Code block can't run the code even the code dont have error

这是我编写的代码,用于根据输入的 x 值查找系列中低于 0.00005 的项。当我 运行 值 x 等于 1 和 2 的代码时,代码工作正常,但是当我输入数字 3 或大于 3 的数字时,代码块似乎与编译器有一些错误。有谁知道我该怎么做才能解决这个问题?

#include <math.h>
#include <stdio.h>
main()
{
    double term=1.0,x;
    int i,fact();

    printf("Enter the value of x: ");
    scanf("%lf",&x);

    for(i=0;term>0.00001;i++){
        term=fabs((pow(-1,i)*pow(x,2*i))/fact(2*i));
    }

    printf("The term become smaller than 0.00005 when term %d reached\n",i );

}

//method for calculating factorial
int fact(int num)
{
    int fact=1;
    for(int i=1;i<=num;++i){
        fact*=i;
    }
    return fact;
}

运行时构造(用户输入)不会导致编译器错误。

如果我们清理您的代码,并向循环添加附加条件,我们可以看到您的计算可以达到无穷大。如果没有这个条件,你的程序将永远循环(给出不工作的外观)。

您需要调整公式或界限。

#include <math.h>
#include <stdio.h>

int fact(int);

int main(void)
{
    double term = 1.0, x;
    int i;

    printf("Enter the value of x: ");
    scanf("%lf", &x);

    for (i = 0; term != INFINITY && term > 0.00001; i++) {
        term = fabs((pow(-1, i) * pow(x, 2 * i)) / fact(2 * i));
        printf("%lf\n", term);
    }

    printf("Final term: %d\n", i);
}

int fact(int num)
{
    int fact = 1;

    for (int i = 1; i <= num; ++i)
        fact *= i;

    return fact;
}

值为2:

Enter the value of x: 2
1.000000
2.000000
0.666667
0.088889
0.006349
0.000282
0.000009
Final term: 7

值为3:

Enter the value of x: 3
1.000000
4.500000
3.375000
1.012500
0.162723
0.016272
0.001109
0.003740
0.021478
0.431218
1.658689
60.034725
363.980804
1371.104161
16628.818145
146096.045130
862879.766548
inf
Final term: 18