-1

This code only outputs 4's and I don't know why. Is it maybe because of the static main or why? thanks

class Calculator {
    public static void main(String[] args) {
    int x = 3;
    boolean op = false;
    int pi = 1;
    for(int i = 0; i < 99999999; i++) {
        if(op == false) {
            pi = pi - 1 / x;
            op = true;
            x = x+2;
            System.out.println(pi*4);
        } else if(op == true) {
            pi = pi + 1 / x;
            op = false;
            x = x+2;
            System.out.println(pi*4);
        }
        
    }
  }
}
  • 1
    `1 / x` is always `0` because this is an int division, and `x` is always greater than 1. – kaya3 Aug 19 '20 at 17:54

2 Answers2

0

As 1 is of type int, and x also has the type int, 1/x will also be an int. Now, because x>3>2 for the whole program, 1/x is always equal to 0. Therefore, pi will always be 1.

To fix this error, I would suggest changing pi to a double and calculation the inverse of x with 1d/x.

CodingTil
  • 447
  • 2
  • 16
0

Below line of code always return constant value as you are trying to do 1/x , it's always gives you 0.33,0.11...

And rounding of it will give you 0.

That's why from pi=pi-0, always return constant value.

        pi = pi - 1 / x;
        op = true;
        x = x+2;
Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38