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