使用绝对函数查找两个数字的最小值

Posted

技术标签:

【中文标题】使用绝对函数查找两个数字的最小值【英文标题】:Find Minimum of two numbers using Absolute function [closed] 【发布时间】:2021-12-09 11:35:22 【问题描述】:

我很难找到至少两个数字,我找到了一个公式,但我认为它是错误的 this is ref

对于最小值:[(x + y + abs(x - y)) / 2] 这是我尝试过的代码

function min(x,y)
/*    var min
    if(x>=y)
         min=y 
     
     else
         min=x
     
     return min 
     */
     return [(x+y + Math.abs(x - y)) / 2]

var x,y;
alert("saisir deux nombre :");
x=+prompt('x:');
y=+prompt('y:');
alert("le min est : " + min(x,y) )
console.log(min(x,y))

测试

x: 1
y: 2
le min est : 2

但他必须给我1

提前致谢

【问题讨论】:

Math.min(1,2); // 1 等等。 Math.min(-2,1); // -2 等。为什么是 absolute ?你的意思是:Math.min(math.abs(-2),Math.abs(1)); // 1 ? 如果您想使用该算法,您引用的那个页面上似乎有一个错误。查看页面底部的 python 代码示例。应该是return [(x+y - Math.abs(x - y)) / 2] --> 减号而不是加号 abs() 我知道我们可以使用 Math.min 这样的预构建函数来实现,但我想用它来实现算法公式: Formulae for Maximum and Minimum of two numbers with a + b and |????−????| and How does one DERIVE the formula for the maximum of two numbers and The Maximum and Minimum of Two Numbers Using the Quadratic Formula 【参考方案1】:

实际公式为((x + y - Math.abs(x - y)) / 2)

function minimum(x,y)
  return ((x + y - Math.abs(x - y)) / 2);


console.log(1, 2, 'minimum', minimum(1,2));
console.log(20, 10, 'minimum', minimum(20,10));
console.log(-20, 10, 'minimum', minimum(-20,10));

【讨论】:

以上是关于使用绝对函数查找两个数字的最小值的主要内容,如果未能解决你的问题,请参考以下文章