gpt4 book ai didi

Java控制台无限次打印 "infinity"而不是值?

转载 作者:行者123 更新时间:2023-12-02 08:52:35 26 4
gpt4 key购买 nike

我正在尝试制作一个程序,用莱布尼兹方程作为 pi 日的属性来估计 pi,但是控制台没有打印出我想要的估计 pi ​​值,而是无限次打印“无穷大”,直到我终止执行。我非常非常困惑,需要帮助!代码:

import java.util.Scanner;
class Main {
public static void main(String[] args) {
//in order to celebrate pi day I have made this program that calculates pi with the Leibniz Formula
System.out.println("enter the number of iterations you want:");
double EstimatedPi=0;
Scanner input= new Scanner(System.in);
double iterations=input.nextDouble();
double denominator = 1;
for(int i=0;0<iterations;i++){
if(i%2 == 0){
EstimatedPi=EstimatedPi + (1/denominator);
}
else{
EstimatedPi=EstimatedPi-(1/denominator);
}
denominator=denominator+2;
EstimatedPi=EstimatedPi*4;
System.out.println(EstimatedPi);
}
}
}

我认为我在整个程序中没有将任何内容除以零!莱布尼兹公式: https://en.wikipedia.org/wiki/Leibniz_formula_for_π控制台截图: screenshot链接到我的 repl 项目: https://repl.it/@HarryPengRHS/Determining-the-value-of-pi-pi-day-attribute

最佳答案

你的for循环条件是错误的,应该是for (int i = 0; i < iterations; i++)您正在使用 for(int i=0;0<iterations;i++){ 0<iterations这始终是正确的,并且循环会无限。

public class Main {

public static void main(String[] args) {// in order to celebrate pi day I have made this program that calculates pi
// with the Leibniz Formula
System.out.println("enter the number of iterations you want:");
double EstimatedPi = 0;
Scanner input = new Scanner(System.in);
double iterations = input.nextDouble();
double denominator = 1;
for (int i = 0; i < iterations; i++) {
if (i % 2 == 0) {
EstimatedPi = EstimatedPi + (1 / denominator);
} else {
EstimatedPi = EstimatedPi - (1 / denominator);
}
denominator = denominator + 2;
EstimatedPi = EstimatedPi * 4;
System.out.println(EstimatedPi);
}
}
}

关于Java控制台无限次打印 "infinity"而不是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689537/

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