【问题标题】:How do to approximate Pi using a while loop and receiving input from the user?如何使用 while 循环来近似 Pi 并接收用户的输入?
【发布时间】:2021-11-15 12:11:06
【问题描述】:

这是我高中计算机科学实验室的第一部分,我想知道是否可以就它为什么不工作以及如何解决它获得一些意见?

“德国数学家戈特弗里德·莱布尼茨(Gottfried Leibniz)开发了以下方法来近似 PI 的值:

Pi 的近似值 第1部分: 编写一个程序,允许用户指定在此近似中使用的迭代次数并显示结果值。使用 while 循环来完成此操作。

样本输出:

您要进行多少次迭代:1000

pi:3.140592653839794"

这是我目前拥有的代码。它无法正常运行,我也不知道为什么或如何修复它。现在我只是想让我的输出样本的输出。谢谢!

//define
    Scanner scnr = new Scanner(System.in);
    double pi = 0.0; 
    double n = 0.0; //number of the term starting from 0
    
    System.out.println("How many iterations would you like to do: ");
    n = scnr.nextInt();

    while (n <= n+1) {
        pi = (Math.pow(-1,n) * 4.0) / (2.0 * n + 1);
        
        System.out.println("pi: " + pi);

【问题讨论】:

  • “这是我目前拥有的代码。它无法正常运行,我也不知道为什么或如何修复它。” -- 是什么让你说这个?为什么您认为它运行不正常?
  • 我的意思是它没有给出我想要的输出。当我输入 1000 作为输入时,我得到无限重复的 pi:0.001999000499750125 而不是 pi:3.140592653839794。我不确定如何解决这个问题。

标签: java while-loop pi


【解决方案1】:

应该这样做:)

        Scanner scnr = new Scanner(System.in);
        double pi = 0.0; 
    
        System.out.println("How many iterations would you like to do: ");
        int n = scnr.nextInt();
        
        int i = 0;
        while (i < n) {
            
            pi += (Math.pow(-1,i) * 4.0) / (2.0 * i + 1);
            
            System.out.println("pi: " + pi);
            i++;
        }

【讨论】:

  • 请注意,您可以使用 for 循环,但为了使其与当前代码相似,我将其保留为 while
  • 非常感谢!!!
猜你喜欢
  • 2023-03-16
  • 2020-10-17
  • 1970-01-01
  • 2013-11-16
  • 2020-02-15
  • 1970-01-01
  • 2017-01-27
  • 2015-12-30
  • 2015-07-03
相关资源
最近更新 更多