เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขที่ไม่เรียงลำดับสามตัว และส่งกลับค่ากลางสุดโดยใช้จำนวนการเปรียบเทียบขั้นต่ำ
ตัวอย่างเช่น หากตัวเลขเป็น −
34, 45, 12
จากนั้นฟังก์ชันของเราจะคืนค่าต่อไปนี้ -
34
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num1 = 34;
const num2 = 45;
const num3 = 12;
const middleOfThree = (a, b, c) => {
// x is positive if a is greater than b.
// x is negative if b is greater than a.
x = a - b;
y = b - c;
z = a - c;
// Checking if b is middle (x and y both
// are positive)
if (x * y > 0) {
return b;
}else if (x * z > 0){
return c;
}else{
return a;
}
};
console.log(middleOfThree(num1, num2, num3)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
34