gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:11:16 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com