Java 计算圆的面积和周长的程序

2025年3月17日 | 阅读 3 分钟

在本节中,我们将创建一个Java 程序来计算圆的面积和周长

圆的面积公式

已知半径时

Java Program to Calculate Area and Circumference of Circle

已知直径时

Java Program to Calculate Area and Circumference of Circle

已知周长时

Java Program to Calculate Area and Circumference of Circle

其中,

A:圆的面积

π:是一个常数,其值为 3.1415 或 22/7。

r:是圆的半径

d:是圆的直径

C:是圆的周长

让我们在 Java 程序中实现上述公式,并找到圆的面积。

在下面的 Java 程序中,我们使用了Java switch case,因为我们使用了三种场景来计算圆的面积。用户提供一个选项,switch 语句执行相应的 case。这三种场景是:已知半径,已知直径,已知周长

注意:在本节中,我们使用了一个常量 Pi (π)。要访问该常量的值,我们使用了 Math 类的静态字段 PI。它在 Math 类中定义如下

最接近 pi 的 double 值,即圆的周长与其直径之比。其值为3.141592653589793。我们可以直接写 pi 的值 (3.14 或 22/7),而不是使用Math.PI

AreaOfCircle.java

输出 1

1. If the radius is known
2. If the diameter is known
3. If the circumference is known
Enter your choice: 1
Enter the radius of the circle: 6
The area of the circle is: 113.09733552923255

输出 2

1. If the radius is known
2. If the diameter is known
3. If the circumference is known
Enter your choice: 2
Enter the diameter of the circle: 16
The area of the circle is: 201.06192982974676

输出 3

1. If the radius is known
2. If the diameter is known
3. If the circumference is known
Enter your choice: 3
Enter the circumference of the circle: 30
The area of the circle is: 71.6197243913529

输出 4

1. If the radius is known
2. If the diameter is known
3. If the circumference is known
Enter your choice: 4
invalid choice!

在下面的 Java 程序中,我们计算了圆的周长。我们在程序中使用的公式是

周长 (C) = 2πr

CircumferenceOfCircle.java

输出

Enter the radius of the circle: 20
The circumference of the circle is: 125.66370614359172

在下面的程序中,我们在一个程序中计算了圆的面积和周长。

AreaAndCircumferenceOfCircle.java

输出

Enter the radius of the circle: 6
The area of the circle is: 113.09733552923255
The circumference of the circle is: 37.69911184307752