java - 我的圆周率计算器有什么问题?

标签 java

我正在使用 Wallis 的方法来计算圆周率,我认为我做对了。至少我认为无论如何我做到了。我认为问题(输出为 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.");
    }
}

最佳答案

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.");
    }
}

关于java - 我的圆周率计算器有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27660576/

相关文章:

java - 我如何/在哪里可以 "stash"/在我的应用程序中保存数据?

java - 统计循环中每个字母的出现次数并显示出现次数最多的字母

java - 如何从java中的特定字符串逐行比较两个文件

java - 如何在 Android 中创建 Fragments 应用程序?

Java ServiceExecutor 终止条件

java - 将参数传递给 Lua 中的对象

java - jdbcTemplate setQueryTimeout 值类型

java - 如何在 JPA 中映射集合映射

java - 如何在 HTTPPOST 请求中将 ArrayList<Integer> 作为 UrlEncodedFormEntity 发送?

java - 使用 RequestHeaderAuthenticationFilter 时如何测试 Internet Explorer?