我的pi计算器出了什么问题?

时间:2014-12-26 18:26:41

标签: java

我使用的是Wallis'计算pi的方法,我想我做对了。至少我想到我还是做了。我认为问题(输出为0)与舍入和余数有关,但我无法确定。这是代码:

import java.util.Scanner;

public class WallisPi {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int a = 2;
        int b = 3;
        int c = 1;
        int pi = 0;
        double acc = 0.0;

        int n = scan.nextInt();
        scan.close();

        for (int i = 0; i <= n; i++) {
            pi = (2 / 3) * c;
            if (a > b) {
                b += 2;
            } else {
                a += 2;
            }
            c = a / b;
        }

        pi *= 4;

        System.out.println("The approximation of pi is " + pi + ".");
        acc = Math.PI - pi;
        System.out.println("It is " + acc + " off.");
    }
}

自发布此消息后,我对代码进行了一些更改,但它仍然不能正常运行。我得到2.666 ......,所以还有其他工作在这里。

import java.util.Scanner;

public class WallisPi {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        double a = 2.0;
        double b = 3.0;
        double c = 1.0;
        double pi = 0;
        double acc = 0.0;

        int n = scan.nextInt();
        scan.close();

        for (int i = 0; i <= n; i++) {
            pi = (2.0 / 3.0) * c;
            if (a > b) {
                b += 2;
            } else {
                a += 2;
            }
            c = a / b;
        }

        pi *= 4;

        System.out.println("The approximation of pi is " + pi + ".");
        acc = Math.PI - pi;
        System.out.println("It is " + acc + " off.");
    }
}

2 个答案:

答案 0 :(得分:6)

int a=2;
int b=3;
double pi=2;
for(int i=0;i<=n;i++){
   pi *= (double)a/(double)b;
  if(a>b){
    b+=2;
  } else {
    a+=2;
  }
}
pi*=2;

使用n = 4000得到3.141200


这是整个程序,已修复:

import java.util.Scanner;

public class WallisPi {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.close();

        double pi = 2;
        int a = 2;
        int b = 3;

        for (int i = 0; i <= n; i++){
            pi *= (double) a / (double) b;
            if (a > b) {
                b += 2;
            } else {
                a += 2;
            }
        }

        pi *= 2;

        double acc = Math.PI - pi;

        System.out.println("The approximation of pi is " + pi + ".");
        System.out.println("It is " + acc + " off.");
    }
}

答案 1 :(得分:0)

由于你的变量是int s,所有的除法都是整数除法,省略了分数(并且只保留了结果的整个部分)。要获得准确的结果,您应将变量定义为double s:

double a=2;
double b=3;
double c=1;
double pi=0;