เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่มีตัวเลขสามตัว (แทนค่าสัมประสิทธิ์ของเทอมกำลังสอง สัมประสิทธิ์ของเทอมเชิงเส้น และค่าคงที่ตามลำดับในสมการกำลังสอง)
และเราจำเป็นต้องค้นหาราก (ถ้าเป็นรากจริง) มิฉะนั้น เราต้องคืนค่าเท็จ มาเขียนโค้ดของฟังก์ชันนี้กัน
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const coefficients = [3, 12, 2];
const findRoots = co => {
const [a, b, c] = co;
const discriminant = (b * b) - 4 * a * c;
if(discriminant < 0){
// the roots are non-real roots
return false;
};
const d = Math.sqrt(discriminant);
const x1 = (d - b) / (2 * a);
const x2 = ((d + b) * -1) / (2 * a);
return [x1, x2];
};
console.log(findRoots(coefficients)); ผลลัพธ์
เอาต์พุตในคอนโซล −
[ -0.17425814164944628, -3.825741858350554 ]