Do you still remember the formula for the volume of a cylinder? Today we will introduce to you how to calculate the volume of a cylinder through JavaScript and keep 4 decimal places~
First of all, let’s recall the formula for the volume of a cylinder:
Volume of a cylinder = base area , or
v=1/2ch×r (half of the side area × radius)Go directly to the code:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <script> function Cylinder(cyl_height, cyl_diameter) { this.cyl_height = cyl_height; this.cyl_diameter = cyl_diameter; } Cylinder.prototype.Volume = function () { var radius = this.cyl_diameter / 2; return this.cyl_height * Math.PI * radius * radius; }; var cyl = new Cylinder(7, 4); console.log('体积 =', cyl.Volume().toFixed(4)); </script> </head> <body> </body> </html>
Note:
PI attribute is π, that is The ratio of the circumference of a circle to its diameter. This value is approximately 3.141592653589793. Its syntax is "Math.PI".
→With an introduction to π:
Pi (π) is the ratio of the circumference to the diameter of a circle. It is generally represented by the Greek letter π and is used in mathematics and physics. A universal mathematical constant. π is also equal to the ratio of the area of a circle to the square of its radius. It is also a key value for accurately calculating geometric shapes such as circle circumference, circle area, and sphere volume. And in analysis, π can be defined very strictly as the smallest positive real number x that satisfies sinx = 0.
Finally, I would like to recommend "JavaScript Basics Tutorial
" ~ Welcome everyone to learn ~The above is the detailed content of Calculate the volume of a cylinder with javascript and keep 4 decimal places. For more information, please follow other related articles on the PHP Chinese website!