Home > Web Front-end > JS Tutorial > body text

JavaScript program to find the area of ​​a circle

WBOY
Release: 2023-09-23 18:29:09
forward
1739 people have browsed it

JavaScript 程序求圆面积

We will use the following formula to calculate the area of ​​a circle -

pi * r^2
Copy after login

In the program, we will prompt the user to enter the radius of the circle. We will then use the formula to calculate the area and print it on the screen.

method

  • Get the radius of the circle from the user as input.

  • Calculate area using the following formula: Area = π * Radius^2

  • Stores the value of π, which can be calculated using Math.PI in JavaScript.

  • Multiply the π value by the square of the radius to get the area.

  • If necessary, use the toFixed() method to round the result to the desired number of decimal places.

  • Return or print the calculated area.

Example

This is an example of a JavaScript program that calculates the area of ​​a circle

const radius = 10;
const pi = Math.PI;
const areaOfCircle = (radius, pi) => {
   return pi * radius * radius;
};
console.log("The area of the circle is: " + areaOfCircle(radius, pi));
Copy after login

illustrate

  • First, we declare two constants: radius and pi. The radius constant is assigned the value 10, and the pi is assigned the value of Math.PI, which is a built-in constant in JavaScript that represents The value of pi (3.14159...).

  • Next, we define a function named areaOfCircle, which accepts two parameters radius and pi.

  • Inside the function, we use the circle area formula, which is pi * radius * radius, and return the result.

  • Finally, we use console.log() to display the results of calling areaOfCircle using radius and pi as parameters . The result is a string that means "The area of ​​a circle is: [area]". This program calculates the area of ​​a circle with radius 10 and prints the result to the console.

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template