首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

藍橋杯圓面積計算:高精度 π 值與格式化輸出 7 位小數

     編輯:程式設計疑難解答

題目要求

  • 輸入整數半徑 r (1~10000)。
  • 輸出面積 π*r*r,**四捨五入保留小數點后 7 位**,格式固定(如 `50.2654825`)。
  • 精度要求高,需用高精度 π。

代碼缺陷

double area = Math.PI * radius * radius; // Math.PI 精度足夠,但輸出格式需嚴格控制
System.out.printf("%.7f", area); // 正確

原代碼邏輯無誤,**關鍵在於 `Math.PI` 精度已足夠(double 15-16 位有效數字),但必須用 `printf("%.7f")` 確保輸出恰好 7 位小數,不多不少。**

高精度 π 替代方案

// 方案1:常量
static final double PI = 3.14159265358979323846;
// 方案2:數學公式
static final double PI = Math.atan(1.0) * 4;
// 方案3:BigDecimal 任意精度(過度設計)

AC 代碼

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt();
        double area = Math.PI * r * r;
        System.out.printf("%.7f\n", area); // 必須換行
    }
}

避坑指南

  • 輸出**必須**恰好 7 位小數,`%.7f` 自動四捨五入補零。
  • 不要多輸出任何提示文本(`System.out.println("請輸入...")` 會導致 WA)。
  • 用 `Scanner` 讀入,關閉後無需 `System.exit(0)`。

總結

`Math.PI` 精度足夠,核心是 `printf("%.7f")` 格式化輸出,且**只輸出結果數字**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved