Wednesday, May 5, 2021

Javascript Practice 34: JS Hero - Math.PI

 
Question: 

Write a function area that calculates the area of a circle. The function is given the radius of the circle.

Example: area(1) should return π and area(2) should return 4 * π.




Answer: 

function area (radius) {

let squared = Math.pow(radius,2); 
let final = Math.PI * squared; 

return final; 
}; 

> Area of a Circle = π * r²
> declared a variable squared and initialized it with a value returned from the Math.pow method
> Math.pow(x, y) returns the value of x to the power of y; Math.pow(radius, 2)
> we then declare another variable final 
> we use the Math.PI method and multiply it to the squared variable to return the value which would be the area
> in the end we return final

No comments:

Post a Comment