Java 程式 - 求圓的周長
對於給定的半徑為 "r" 的圓,編寫一個 Java 程式求該圓的周長。周長 也稱為圓的邊緣長度。它是繞圓一週的距離。
周長 由公式C = 2𝜋r給出,其中,pi/𝜋 = 3.14,r 是圓的半徑 −

示例情境
Input: radius = 5 Output: perimeter = 31.400000000000002
2 * 3.14 * 5 = 31.428571428571427
定義 PI 的常量
在此 Java 程式中,我們定義 PI 的值為常量,並使用它求圓的周長。
public class PerimeterOfCircle {
// defining constant
static final double PICONST = 3.14;
public static void main(String args[]) {
double my_radius, my_perimeter;
my_radius = 5;
System.out.println("The radius of the circle is defined as " +my_radius);
my_perimeter = PICONST * 2 * my_radius;
System.out.println("The perimeter of Circle is: " + my_perimeter);
}
}
輸出
The radius of the circle is defined as 5.0 The perimeter of Circle is: 31.400000000000002
使用 Math.PI
在以下示例中,我們使用 Math.PI 來計算圓的周長。
public class PerimeterOfCircle {
public static void main(String args[]) {
double my_radius, my_perimeter;
my_radius = 7;
System.out.println("The radius of the circle is defined as " + my_radius);
my_perimeter = Math.PI * 2 * my_radius;
System.out.println("The perimeter of Circle is: " + my_perimeter);
}
}
輸出
The radius of the circle is defined as 7.0 The perimeter of Circle is: 43.982297150257104
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP