1

You need to find the sums of an infinite series with a given accuracy.(the picture with the task is given as a link) the program constantly counts the zero amount. I don't understand what my mistake is

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
    int i;
    int n =1;
    double E,x,q;
    double sum = 0;

    scanf ("%f",&E) ;
    scanf ("%f",&x) ;

    q=pow(x,3)/6;

    while(fabs(q)>=E){

        if (n/2==0) {
            sum=sum+q;
        }
        else {
            sum=sum-q;
        }
        q=(q*pow(x,2))/(n+3);
        n=n+1;
    }
    printf("%f",sum);
    return 0;
}
3
  • Is your if statement right? Don't you mean n%2 == 0.
    – moritz
    Nov 1, 2020 at 5:27
  • Maybe I need to check whether n is even or not.The program started producing at least some non-zero result after I changed f to lf.But I still don't know if I did this program correctly. #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int i; int n =1; double E,x,q; double sum = 0; printf("enter E = "); scanf ("%lf",&E) ; printf("enter x = "); scanf ("%lf",&x) ; q=pow(x,3)/3; while(fabs(q)>=E){ if (n%2==0) {sum=sum+q;} else { sum=sum-q;} q=(q*pow(x,2)*(2*n+1))/(2*n+8); n=n+1; } printf("%d %lf", n-1, sum); return 0; }
    – user14556999
    Nov 1, 2020 at 11:02
  • "Maybe I need to check whether n is even or not." n%2 == 0 does exactly this. Maybe you can update your question and leave a note about the improvements. Or if you have a new problem write a new one.
    – moritz
    Nov 1, 2020 at 11:31

1 Answer 1

2

It will never going to enter to that if statement. You are letting n=1 and it will be always 1, and u are doing n=n+1 in the else.

3
  • The code will enter the first if directly. By calculating with Integers 1/2 = 0. And he does increment the int after the else. After the first iteration the code will never enter the if.
    – moritz
    Nov 1, 2020 at 5:21
  • He changed the code. Now the problem is other i see...
    – b3lg1c4
    Nov 1, 2020 at 5:38
  • ah okay, sorry.
    – moritz
    Nov 1, 2020 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy