3
06/11/2024 10:28 am
Rozpoczęcie tematu
JS task: Write a JavaScript function that calculates a triangle’s area by its 3 sides.
- The input comes as 3 (three) number arguments, representing one sides of a triangle.
- The output should be printed to the console.
Example:
Input:
2
3.5
4
Output:
3.4994419197923547
1 Odpowiedź
2
06/11/2024 10:30 am
For this task you must use the Heron's formula:
https://en.wikipedia.org/wiki/Heron%27s_formula
Here's my solution to it (with Heron's formula):
function triangleArea(a, b, c) {
let sp = (a + b + c) / 2;
let area = Math.sqrt(sp * (sp - a) * (sp - b) * (sp - c));
console.log(area);
}
triangleArea(2, 4, 3.5);
Or with .map(Number) which transform all the elements of the array into numbers.
See line 2:
function areaTriangle([a,b,c]) {
[a,b,c] = [a, b, c].map(Number);//.map is converting all the elements in the array into numbers
let sp = (a + b + c) / 2;
let area = Math.sqrt(sp * (sp - a) * (sp - b) * (sp - c));
return area;
}
console.log(areaTriangle(["2", "3.5", "4"]));
