1

We got an assignment where we have to calculate the value of pi using the formula pi/4=1-1/3+1/5-1/7+1/9-1/11...(using 100 terms) but it doesn't seem to run the while-loop for some reason. We're students who have no prior experience of writing code and are just starting.

double pi = 1;
int count = 0;
int n = 3;

while (count < 100) {
    if ((count&1) == 0) {  
        pi = pi - 1 / n;
    } else {
        pi = pi + 1 / n;
    }
    n = n + 2;
    count++;
}
out.print(pi*4);   //why is it printing out pi=1?????
3
  • first your 'if ' is wrong. && use this. Commented Sep 3, 2016 at 14:22
  • 1
    1/n will be always 0 as you are divide int by int and result is int also Commented Sep 3, 2016 at 14:23
  • consider using += or -= operators to increment/decrement your variable Commented Sep 3, 2016 at 14:31

1 Answer 1

7

The problem is you do not type cast. pi is double but 1/n returns int, since both the denominator and numerator are integers. This happens in JAVA. Basically, every time, 1/n which is actually fractional, returns 0 (int) for every n > 1 due to lack of type casting. So pi's value is always 1 and in the end pi*4 displays 4.0. So you have to convert (cast) the numerator or the denominator as fractional (double) to make 1/n fractional.

To solve the problem, change the statements

pi = pi + 1 / n;
pi = pi - 1 / n;

to

pi = pi + 1.0 / (double) n;
pi = pi - 1.0 / (double) n;

This displays the output as 3.1514934010709914.

Sign up to request clarification or add additional context in comments.

3 Comments

no need to cast n as double since 1.0 is a double, the result will be a double
@NicolasFilotto yes. But that's just to show the OP what exactly I'm trying to do. Plus it helps understand better.
thank you. we solved it by declaring n as a double though. at the time we were still learning about int and double.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.