Home  >  Article  >  Web Front-end  >  JavaScript program to find the area and perimeter of a rectangle

JavaScript program to find the area and perimeter of a rectangle

王林
王林forward
2023-08-30 14:05:03760browse

JavaScript 程序求矩形的面积和周长

We are writing a JavaScript program to calculate the area and perimeter of a rectangle. The program will prompt the user to enter the width and length of the rectangle, and we will then use these values ​​to calculate the area and perimeter. We will keep using these formulas: Area = Width * Length and Perimeter = 2 * (Width Length) to find the desired measurements.

method

The method to find the area and perimeter of a rectangle in JavaScript can be done as follows -

  • Use variables to define the length and width of the rectangle.

  • Calculate the area by multiplying the length and width of the rectangle.

  • Calculate the perimeter by adding twice the length and twice the width of the rectangle.

  • Display results for area and perimeter.

  • Store the result in a variable and return the value when needed.

  • Repeat the above steps for different length and width groups as needed.

Example

This is an example of a JavaScript program that calculates the area and perimeter of a rectangle -

// Function to find the area of a rectangle
function findArea(width, height) {
   return width * height;
}
// Function to find the perimeter of a rectangle
function findPerimeter(width, height) {
   return 2 * (width + height);
}

// Input for width and height
var width = 5;
var height = 10;

// Calculate the area and perimeter
var area = findArea(width, height);
var perimeter = findPerimeter(width, height);

// Output the results
console.log("Area of rectangle: " + area);
console.log("Perimeter of rectangle: " + perimeter);

explain

  • First define two functions - findArea and findPerimeter to calculate the area and perimeter of the rectangle respectively.

  • findArea The function takes two parameters - width and height and returns the result of width * height.

  • findPerimeter The function takes two parameters - width and height and returns 2 * (width height).

  • The width and height of the rectangle are defined by var width = 5 and var height = 10.

  • The area and perimeter of a rectangle are calculated using the findArea and findPerimeter functions and stored in the variables area and perimeter.

  • Finally, use console.log to output the results to the console and display them in the format of "Rectangle Area: X" and "Rectangle Perimeter: Y", where X is the area, Y is the perimeter.

The above is the detailed content of JavaScript program to find the area and perimeter of a rectangle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete