Skip to content
Advertisement

Java console printing out “infinity” infinite times instead of value?

I am trying to make a program that estimates pi with the Leibniz equation as an attribute to pi day, however instead of printing out the estimated pi value that I wanted the console is printing out “infinity” for infinite times until I terminate the execution. I am very very confused, help needed! code:

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    //in order to celebrate pi day I have made this program that calculates pi with the Leibniz Formula
     System.out.println("enter the number of iterations you want:");
    double EstimatedPi=0;
    Scanner input= new Scanner(System.in);
    double iterations=input.nextDouble();
    double denominator = 1;
    for(int i=0;0<iterations;i++){
      if(i%%2 == 0){
        EstimatedPi=EstimatedPi + (1/denominator);
      }
      else{
        EstimatedPi=EstimatedPi-(1/denominator);
      }
      denominator=denominator+2;
      EstimatedPi=EstimatedPi*4;
      System.out.println(EstimatedPi);
    }
  }
}

I don’t think I divided anything by zero in the entire program! the Leibniz formula: https://en.wikipedia.org/wiki/Leibniz_formula_for_π console screenshot: screenshot link to my repl project: https://repl.it/@HarryPengRHS/Determining-the-value-of-pi-pi-day-attribute

Advertisement

Answer

Your for loop condition is wrong it should be for (int i = 0; i < iterations; i++) you were using for(int i=0;0<iterations;i++){ 0<iterations which is always true and loop goes to infinite.

public class Main {

    public static void main(String[] args) {// in order to celebrate pi day I have made this program that calculates pi
                                            // with the Leibniz Formula
        System.out.println("enter the number of iterations you want:");
        double EstimatedPi = 0;
        Scanner input = new Scanner(System.in);
        double iterations = input.nextDouble();
        double denominator = 1;
        for (int i = 0; i < iterations; i++) {
            if (i %% 2 == 0) {
                EstimatedPi = EstimatedPi + (1 / denominator);
            } else {
                EstimatedPi = EstimatedPi - (1 / denominator);
            }
            denominator = denominator + 2;
            EstimatedPi = EstimatedPi * 4;
            System.out.println(EstimatedPi);
        }
    }
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement