settingsAccountsettings
Menusettings

Q: Calculate the volume and surface area of a cone in JavaScript

+4 votes

I have to write a JavaScript function to calculate a cone’s volume and surface area by given height and radius at the base.

The input comes as two number arguments:

  1. The first element is the cone’s radius
  2. The second is its height

Example:

Input:
3
5

Output:
volume = 47.1239
area = 83.2298


Input:
3.3
7.8

Output:
volume = 88.9511
area = 122.016

The output should be printed to the console on a new line for every result.

asked in JavaScript category by user matthew44

2 Answers

+3 votes

You need to undesrtand how to calculate the volume and the surface of a cone. See the image below to get a better understanding;

cone volume and surface formula

Here is the code with the solution:

function cone(input) {
    let [r,h]=input.map(Number);
    let s = Math.sqrt(r * r + h * h);
    let volume = Math.PI * r * r * h / 3;
    console.log("volume = " + volume);
    let area = Math.PI * r * (r + s);
    console.log("area = " + area);
}

cone(["3.3", "7.8"]);

You can check the results here: https://www.calculatorsoup.com/calculators/geometry-solids/cone.php

answered by user eiorgert
edited by user golearnweb
+2 votes

This is my solution for the first input 3 and 5:

function coneTask(a, b) {
    let s = Math.sqrt(a * a + b * b);
    let volume = Math.PI * a * a * b / 3;
    console.log("volume = " + volume);
    let area = Math.PI * a * (a + s);
    console.log("area = " + area);
}

coneTask(3, 5);
answered by user paulcabalit
...