Java程式:求矩形的周長
對於給定長為l,寬為w的矩形,編寫一個Java程式來求其周長。矩形的周長是矩形所有邊長的總和。
下面是一個矩形的示意圖,它是一個具有四個直角(90°)的四邊形。矩形的周長是矩形的兩條長和兩條寬的總長度:

示例場景
Input: length = 5, 8, 5, 8; Output: Perimeter = 26
將矩形所有邊長相加,即可得到周長:5+8+5+8 = 26
在Java中求矩形周長的步驟
按照以下步驟計算矩形的周長:
步驟1 – 開始
步驟2 – 宣告並初始化矩形的長、寬和周長。
步驟3 – 透過將所有邊長相加或使用周長公式來計算周長。
步驟4 – 顯示周長值。
步驟5 – 結束
示例1
以下示例演示如何在Java中計算矩形的周長。
public class RectanglePerimeter {
public static void main(String[] args) {
// length of the rectangle
double length = 9.0;
// width of the rectangle
double width = 7.0;
// perimeter of the rectangle
double perimeter = 2 * (length + width);
System.out.println("The perimeter of rectangle is: " + perimeter);
}
}
輸出
The perimeter of rectangle is: 32.0
示例2
這是另一個Java程式,它演示如何求矩形的周長。
public class RectanglePerimeter{
public static void main (String args[]){
float a ,b, c, d, perimeter;
a=c= 8;
b=d= 5;
System.out.printf("The length of the sides of the Rectangle are %.2f %.2f %.2f %.2f", a, b, c, d);
perimeter = a + b + c + d;
System.out.printf("\nThe perimeter of Rectangle is: %.2f",perimeter);
}
}
輸出
The length of the sides of the Rectangle are 8.00 5.00 8.00 5.00 The perimeter of Rectangle is: 26.00
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP