i keep getting infinity as an output in my code

83 Views Asked by At
#include <stdio.h>
#include <math.h>
int i;
double result = 0;
int terms;
int term;
double stage1;
double stage2;
double zeta(int terms){
    for (i=0; i != terms; i++){
        result += 1 / pow(i, 2);

    }
    return result;
}
double pi(int term){
    stage1 = zeta(term) * 6;
    stage2 = sqrt(stage1);
  return stage2;

}
int main(){
    printf("the terms?:");
    scanf("%d", &term);
    pi(term);
    printf("%f", pi(term));

}

i wrote this code that uses the zeta function to calculate pi but it keeps outputting infinity no matter how many terms i tried python and it works normally there any ideas on how to fix it?

i looked into it and i think it might be the math library because it does output infinity i was at least expecting an approximation of pi but it did not even output that it just outputted infinity

1

There are 1 best solutions below

0
Bruno On BEST ANSWER

Try:

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

double zeta(int terms)
{
    double result = 0;
    for (int i = 1; i < terms; i++)
        result += 1 / pow(i, 2);
    return result;
}

double pi(int term)
{
    return sqrt(zeta(term) * 6);
}

int main()
{
    int term;
    printf("the terms: ");
    scanf("%d", &term);
    printf("%f\n", pi(term));
}

I only changed the for loop, starting from 1 instead of zero (reading briefly about the zeta function, I hope I understood it - sorry if I am wrong here).

I also moved variables inside functions (= the place where they are used), something you should always do. You will note that even the variable i in zeta function is declared in a narrower scope (the for loop scope, not the function scope).