1

So here is a program that is supposed to calculate an approximation to the value of pi if you take enough terms into the sum which is mathematically described in the following program and calculates the expression of the root, you get a value that gets closer and closer to the value of pi the more terms you have.

#include <stdio.h> #include <math.h> main() { int j, terms; double sum, precision, pi; printf("How many terms: "); scanf("%d", &terms); for(j=1;j<=terms;j++) sum+=1/(j*j); pi = sqrt(6*sum); printf("Pi: %lf.\n", pi); } 

But there is something making it go wrong here and I can't quite figure out what.

sum+=1/(j*j); 

I thought the mistake might be in that line because all others look fine,thinking at first maybe the computer isn't counting decimals.I'm unsure.But my question is: What is it in this code that makes it malfunction?And how do I fix it?

8
  • In what way is it going wrong? Commented Mar 23, 2012 at 8:34
  • You could also try the Monte Carlo method - you might get extra marks for that! Commented Mar 23, 2012 at 8:39
  • 1
    @EdHeal I wouldn't bet on that. Sounds like a gamble. Commented Mar 23, 2012 at 8:41
  • 1
    I see you are using a C89 compiler (no return type specified for main, compiler assumes int) ... oh! wait ... it's a C99 compiler after all (no return statement inside main, compiler assumes return 0;) ... but but ... C89 and C99 at the same time is a really strange compiler :) Suggestion: specify the return type of main and specify a return statement. Commented Mar 23, 2012 at 9:05
  • 1
    Just for clarity, why not add an initializer to the declaration double sum=0.0... Commented Mar 23, 2012 at 13:22

1 Answer 1

7

This performs integer division:

1/(j*j); 

try this:

sum+=1.0/(j*j); 

If j*j might overflow, do this

sum+=1.0/((double)j*j); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.