[英]How do I get the absolute value of an integer without using Math.abs?
How do I get the absolute value of a number without using math.abs?如何在不使用 math.abs 的情况下获得数字的绝对值?
This is what I have so far:这是我到目前为止所拥有的:
function absVal(integer) {
var abs = integer * integer;
return abs^2;
}
You can use the conditional operator and the unary negation operator : 您可以使用条件运算符和一元否定运算符 :
function absVal(integer) {
return integer < 0 ? -integer : integer;
}
You can also use >> (Sign-propagating right shift)
你也可以使用
>> (Sign-propagating right shift)
function absVal(integer) {
return (integer ^ (integer >> 31)) - (integer >> 31);;
}
Note: this will work only with integer 注意:这仅适用于整数
Since the absolute value of a number is "how far the number is from zero", a negative number can just be "flipped" positive (if you excuse my lack of mathematical terminology =P): 由于数字的绝对值是“数字从零到多远”,因此负数可以“翻转”为正数(如果您原谅我缺乏数学术语= P):
var abs = (integer < 0) ? (integer * -1) : integer;
Alternatively, though I haven't benchmarked it, it may be faster to subtract-from-zero instead of multiplying (ie 0 - integer
). 或者,虽然我没有对它进行基准测试,但是从零减去而不是乘以(即
0 - integer
)可能会更快。
Late response, but I think this is what you were trying to accomplish:迟到的回应,但我认为这是你想要完成的:
function absVal(integer) {
return (integer**2)**.5;
}
It squares the integer then takes the square root.它平方 integer 然后取平方根。 It will eliminate the negative.
它将消除负面影响。
There's no reason why we can't borrow Java's implementation . 我们没有理由不借用Java的实现 。
function myabs(a) { return (a <= 0.0) ? 0.0 - a : a; } console.log(myabs(-9));
How this works: 这是如何工作的:
> 0
> 0
> 0
) > 0
) Check if the number is less than zero! 检查数字是否小于零! If it is then mulitply it with -1;
如果是那么多了它-1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.