简体   繁体   中英

Java Pi calculator getting stuck

I recently made a Pi calculator in Java and when I run it, it defines Pi down to the same amount incredibly fast but then it gets stuck at 3.141592653589787 and only outputs that. Here's my code if anyone can help figure out what's happening.

public static void main(String[] args) {
    double a = 2;
    double b = 3;
    double c = 4;
    double z = 3;

    while (true) {
        double x = a*b*c;
        double y = 4/x;
        z+=y;
        a+=2;
        b+=2;
        c+=2;

        x = a*b*c;
        y = 4/x;
        z-=y;
        a+=2;
        b+=2;
        c+=2;
        System.out.println(z);
    }
}

I would rather use this code for the PI approach from the rectangles approximates:

    int rectangleCount = 100;
    double width = 0.0;
    double pi = 0.0;
    double height = 0.0;
    double radius = 1.0;
    
    for (int i = 1; i <= rectangleCount; i++) {
        
        width = (double)i / rectangleCount;
        
        height = Math.sqrt(radius - width*width);
        
        pi = pi + (radius/rectangleCount) *height;
    }
    pi = pi + 1.0/rectangleCount; //first rectangle

    System.out.println(pi*4);

Basically the count of the rectangles you choose, doesn't matter. The first rectangle always has the same radius and width, while the rest of the rectangles can be calculated in the for loop.

What's the purpose of this program. Looks lke it's overcomplex :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM