บทความนี้สาธิตฟังก์ชันคำนวณความยาวด้านตรงข้ามมุมฉาก (hypotenuse) จากฐานและสูง โดยใช้ทฤษฎีบทพีทาโกรัส
ตัวอย่าง
base = 8, perpendicular = 6 -> hypotenuse = 10
ตัวอย่างโค้ด
const base = 8;
const perpendicular = 6;
const findHypotenuse = (base, perpendicular) => {
const bSquare = base ** 2;
const pSquare = perpendicular ** 2;
const sum = bSquare + pSquare;
const hypotenuse = Math.sqrt(sum);
return hypotenuse;
};
console.log(findHypotenuse(base, perpendicular));
console.log(findHypotenuse(34, 56));
ผลลัพธ์
10 65.5133574166368
คำอธิบาย
ใช้สูตร c = √(a² + b²) โดย a = base, b = perpendicular
JavaScript มี Math.hypot() สำหรับคำนวณ hypotenuse ได้โดยตรง: Math.hypot(base, perpendicular)