Trong bài viết này, chúng ta sẽ tìm hiểu cách tính chu vi hình chữ nhật. Chu vi hình chữ nhật được tính bằng cách cộng độ dài tất cả các cạnh.
Dưới đây là minh họa hình chữ nhật. Chu vi là tổng độ dài hai chiều dài và hai chiều rộng:

Đầu vào
Giả sử đầu vào:
Độ dài các cạnh hình chữ nhật: 5, 8, 5, 8
Đầu ra
Kết quả mong đợi:
Chu vi: 26
Thuật toán
Bước 1 – BẮT ĐẦU Bước 2 – Khai báo 5 biến float: a, b, c, d, perimeter Bước 3 – Đọc giá trị a, b từ người dùng (cạnh đối diện bằng nhau nên chỉ cần 2 cạnh) Bước 4 - Tính chu vi bằng cách cộng tất cả các cạnh Bước 5 - Hiển thị chu vi Bước 6 – DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.
import java.util.Scanner;
public class RectanglePerimeter {
public static void main(String args[]) {
float a, b, c, d, perimeter;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A Scanner object has been defined");
System.out.print("Enter the length of first side: ");
a = my_scanner.nextFloat();
System.out.print("Enter the length of second side: ");
b = my_scanner.nextFloat();
c = a;
d = b;
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);
}
}
Đầu ra
Required packages have been imported A Scanner object has been defined Enter the length of first side: 5 Enter the length of second side: 8 The length of the sides of the Rectangle are 5.00 8.00 5.00 8.00 The perimeter of Rectangle is: 26.00
Ví dụ 2: Giá trị định nghĩa trước
Các cạnh đã được định nghĩa trước.
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);
}
}
Đầu ra
The length of the sides of the Rectangle are 8.00 5.00 8.00 5.00 The perimeter of Rectangle is: 26.00