-3
#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

  • 6
    `1 / pow(i, 2)` What would be the value for this when `i==0`? – Eugene Sh. May 17 '23 at 16:57
  • 1
    please move global variables inside functions – Renat May 17 '23 at 16:58
  • 2
    And why did you dump the entire program for other people to analyze instead of breaking it into parts and examining the steps yourself? Simply printing the value of `result` in each iteration of the loop would have revealed it become infinity in the first iteration, and then you could have examined the value of `1 / pow(i, 2)` in the first iteration. Debugging questions should be presented with a [mre], and the “minimal” in that means reducing the code, including finding the first point where a problem occurs. – Eric Postpischil May 17 '23 at 17:59
  • i'm new to coding in C i learned it for this specific project please forgive me of my shortcomings as i do not have the experience yet to know what to do – Yazan Ahmad May 17 '23 at 18:45

1 Answers1

0

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).

Bruno
  • 580
  • 5
  • 14