Java 程序求矩形的面积


2022年3月13日, Learn eTutorial
1300

这里我们解释如何计算矩形的面积。

 如何计算矩形的面积?

矩形有四条边,其中两条相邻的边相等。矩形的面积通过将矩形的长度乘以矩形的宽度来计算。

矩形面积 = 长 * 宽

其中 l 是矩形的长度,w 是矩形的宽度。

如何实现 Java 程序来求矩形的面积?

首先,我们必须声明类 AreaRect。创建一个 Scanner 类的对象 sc,并使用 nextDouble() 方法从用户那里读取矩形的长度和宽度到变量 l,w 中。计算面积为 a=l*w。使用 System.out.println() 显示面积 a

算法

步骤 1: 声明具有 public 修饰符的类 AreaRect

步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始

步骤 3: 声明变量 l,w,a 为 double 类型。

步骤 4: 读取矩形的长度 l

步骤 5: 读取矩形的宽度 w

步骤 6: 计算矩形的面积 a=l*w

步骤 7: 显示面积 a

 

Java 源代码

                                          import java.util.Scanner;
public class AreaRect{
   public static void main(String args[]) {   
       double l,w,a;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the length of the Rectangle:");
      l = sc.nextDouble();
      System.out.println("Enter the width of the Rectangle:");
      w = sc.nextDouble();

      a = l*w;
      System.out.println("The Area of the Rectangle is: " + a);    
   }
}
                                      

输出

Enter the length of the Rectangle:10
Enter the width of the Rectangle:20
The Area of the Rectangle is:200.0