Home > Back-end >  Code block can't run the code even the code dont have error
Code block can't run the code even the code dont have error

Time:12-02

This is the code i wrote to find the term that is lower than 0.00005 in a series depends on the value of x entered. When i run the code with value x equal to 1 and 2 the code work fine, but when i enter number 3 or number that is more than 3, code block seems to have some error with the compiler. Does anyone know what can i do to fix this?

#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;
}

CodePudding user response:

A runtime construct (user input) can not cause a compiler error.

If we clean up your code, and add an additional condition to the loop we can see that your calculations can reach towards infinity. Without this condition your program will loop forever (giving the appearance of not working).

You'll need to adjust your formula, or your bounds.

#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;
}

With a value of 2:

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

With a value of 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
  • Related