You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何通过用户输入设置阈值改写π近似迭代计算程序

关于是否需要使用DecimalFormat的说明

不需要。DecimalFormat的核心用途是格式化数值的输出显示样式,不负责存储阈值、参与精度判断逻辑。你只需直接用double类型接收用户输入的阈值,后续直接拿该值做差值校验即可。
如果后续你需要固定输出的小数位数,才需要用到DecimalFormat,使用示例如下:

// 示例:固定输出8位小数
DecimalFormat df = new DecimalFormat("#.########");
System.out.println("格式化后的pi值:" + df.format(pi));
满足需求的改写后代码

完整实现代码如下,已经适配了用户指定阈值停止迭代、输出指定内容的要求:

import java.util.Scanner;

public class PiCalculator {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        double pi = 0.0;
        int iterationCount = 0;

        // 接收用户输入的阈值
        System.out.print("What is the threshold you wish to use: ");
        double threshold = scnr.nextDouble();

        // 迭代计算直到精度满足要求
        while (Math.abs(pi - Math.PI) > threshold) {
            pi += (Math.pow(-1, iterationCount) * 4.0) / (2.0 * iterationCount + 1);
            iterationCount++;
        }

        // 按要求输出结果
        System.out.printf("Math.PI:     %.15f%n", Math.PI);
        System.out.printf("pi:          %.15f%n", pi);
        System.out.println("Number of iterations: " + iterationCount);

        scnr.close();
    }
}

内容的提问来源于stack exchange,提问作者sir gregor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:24:03