Home > Article > Web Front-end > JavaScript program to find the area of a circle
We will use the following formula to calculate the area of a circle -
pi * r^2
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.
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.
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));
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!