gpt4 book ai didi

java - 查找 PI 具有特定值的术语

转载 作者:行者123 更新时间:2023-12-01 12:47:54 25 4
gpt4 key购买 nike

我有点难以从无穷级数计算 π 的值:

π = 4 – 4/3 + 4/5 – 4/7 + 4/9 – 4/11 + ...

必须解决的问题是“打印一张表格,显示通过计算该系列的前 200,000 项近似得出的 π 值。在您第一次得到以 3.14159 开头的值之前,您必须使用多少项?”

我不确定我用于查找该术语的条件是否正确。有人可以告诉我这是否正确,如果不是,那么正确的方法是什么?我怀疑它与 Java 如何舍入数字有关。

package com.company;

public class Main {

public static void main(String[] args) {

double result = 0;
int j = 1;
int k = 1; //controls the if part for finding the term
int term = 0; //variable for term that we're looking for

for (int i = 1; i <= 200000; i += 1) {

if ((i % 2) != 0) {
result += (double) 4 / j; //positive part
j += 2;
}
else {
result -= (double) 4 / j; //negative part
j += 2;
}

if (k != 0) {

/* Attempts to detect when result == 3.14159 */

if (result > 3.14158 && result < 3.14160) {
term = i;
k = 0;
}
}

System.out.printf("%f\n", result);
}

System.out.println("Term at which pi has value 3.14159: " + term);
}
}

最佳答案

Java Math类(class)是你的 friend 。文档在这里:https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

我倾向于使用 Math.floor(result * 100000) == 314159) 进行测试

您可能还想包括 i在您的结果中,以便您可以轻松地对照表格检查您的答案。

最后,我会使用 boolean而不是 int为测试。

关于java - 查找 PI 具有特定值的术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60491991/

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