三個元素的中值 - JavaScript
我們需要編寫一個 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
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP