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 任意精度(過度設計)
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); // 必須換行
}
}
`Math.PI` 精度足夠,核心是 `printf("%.7f")` 格式化輸出,且**只輸出結果數字**。