Java 程式 - 求圓的周長


對於給定的半徑為 "r" 的圓,編寫一個 Java 程式求該圓的周長。周長 也稱為圓的邊緣長度。它是繞圓一週的距離。

周長 由公式C = 2𝜋r給出,其中,pi/𝜋 = 3.14r 是圓的半徑 −


示例情境

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

更新於: 15/8/2024

984 次瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.