三个元素的中值 - 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

更新于: 16-Sep-2020

280 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告