将负数变为正数
我有一个 Java 方法,可以对一组数字求和。 但是,我希望将任何负数视为正数。 所以 (1)+(2)+(1)+(-1) 应该等于 5。
我确信有一个非常简单的方法可以做到这一点 - 我只是不知道如何做。
I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.
I'm sure there is very easy way of doing this - I just don't know how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
当您需要表示一个没有损失或缺失(负值)概念的值时,这称为“绝对值”。
获取绝对值的逻辑非常简单:
“如果是正数,则维持它。如果是负数,则取反”
。这意味着您的逻辑和代码应如下所示工作:
有 2 种方法可以对某个值取反:
value = (-value);
值 = 值 *
(-1);
两者实际上是同一枚硬币的两面。 只是您通常不记得
value = (-value);
实际上是value = 1 * (-value);
。好吧,至于在 Java 中实际如何做到这一点,非常简单,因为 Java 已经在 Math 类中提供了一个函数: value = Math.abs(value);< /code>
是的,不使用
Math.abs()
就只是一行非常简单的数学代码,但是为什么让你的代码看起来很丑呢? 只需使用 Java 提供的Math.abs()
函数即可! 他们提供它是有原因的!如果您绝对需要跳过该函数,可以使用 value = (value < 0) ? (-value) : value;,这只是我在逻辑(第三)部分中提到的代码的更紧凑版本,使用 三元运算符 (
? :
)。此外,在某些情况下,您可能希望始终表示函数中的丢失或缺失,该函数可能同时接收正值和负值。
您可以简单地获取绝对值并将其取反,而不是进行一些复杂的检查:
negativeValue = (-Math.abs(value));
考虑到这一点,并考虑具有总和的情况对于像您这样的多个数字,实现一个函数是一个好主意:
根据您可能再次需要相关代码的可能性,将它们添加到您自己的“utils”库中,拆分这些函数也可能是一个好主意首先进入它们的核心组件,并将最终函数简单地维护为对核心组件现在拆分的函数的调用嵌套:
When you need to represent a value without the concept of a loss or absence (negative value), that is called "absolute value".
The logic to obtain the absolute value is very simple:
"If it's positive, maintain it. If it's negative, negate it"
.What this means is that your logic and code should work like the following:
There are 2 ways you can negate a value:
value = (-value);
value = value *
(-1);
Both are actually two sides of the same coin. It's just that you usually don't remember that
value = (-value);
is actuallyvalue = 1 * (-value);
.Well, as for how you actually do it in Java, it's very simple, because Java already provides a function for that, in the
Math class
:value = Math.abs(value);
Yes, doing it without
Math.abs()
is just a line of code with very simple math, but why make your code look ugly? Just use Java's providedMath.abs()
function! They provide it for a reason!If you absolutely need to skip the function, you can use
value = (value < 0) ? (-value) : value;
, which is simply a more compact version of the code I mentioned in the logic (3rd) section, using the Ternary operator (? :
).Additionally, there might be situations where you want to always represent loss or absence within a function that might receive both positive and negative values.
Instead of doing some complicated check, you can simply get the absolute value, and negate it:
negativeValue = (-Math.abs(value));
With that in mind, and considering a case with a sum of multiple numbers such as yours, it would be a nice idea to implement a function:
Depending on the probability you might need related code again, it might also be a good idea to add them to your own "utils" library, splitting such functions into their core components first, and maintaining the final function simply as a nest of calls to the core components' now-split functions:
为什么不
将该数字乘以-1
?像这样:
Why don't you
multiply that number with -1
?Like This:
如果您对二进制补码的机制感兴趣,下面是绝对低效但具有说明性的低级方法:
If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:
可以使用库函数
Math.abs()
。Math.abs()
返回参数的绝对值例如:
int x=-5;
System.out.println(Math.abs(x));
输出:5
int y=6;
System.out.println(Math.abs(y));
输出:6
Library function
Math.abs()
can be used.Math.abs()
returns the absolute value of the argumente.g:
int x=-5;
System.out.println(Math.abs(x));
Output: 5
int y=6;
System.out.println(Math.abs(y));
Output: 6
或者:
Alternatively:
要将负数转换为正数(这称为绝对值),请使用 Math.abs()。 Math.abs() 方法的工作原理如下
“number = (number < 0 ? -number : number);”。
在下面的示例中,
Math.abs(- 1)
将负数 1 转换为正数 1。public static void main(String[] args) {
To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this
“number = (number < 0 ? -number : number);".
In below example,
Math.abs(-1)
will convert the negative number 1 to positive 1.public static void main(String[] args) {
我会推荐以下解决方案:
不使用 lib fun:
(上述内容实际上不起作用。)
使用 lib fun:
I would recommend the following solutions:
without lib fun:
(The above does not actually work.)
with lib fun:
我看到人们在说
Math.abs(number)
但这个方法并不能完全证明。当您尝试换行
Math.abs(Integer.MIN_VALUE)
时,此操作会失败(请参阅参考文献。 https://youtu.be/IWrpDP-ad7g)如果您不确定是否会收到输入中的
Integer.MIN_VALUE
。 始终建议检查该号码并手动处理。I see people are saying that
Math.abs(number)
but this method is not full proof.This fails when you try to wrap
Math.abs(Integer.MIN_VALUE)
(see ref. https://youtu.be/IWrpDP-ad7g)If you are not sure whether you are going to receive the
Integer.MIN_VALUE
in the input. It is always recommended to check for that number and handle it manually.我需要 long 的绝对值,并深入研究 Math.abs 并发现如果我的参数小于 LONG.MIN_VAL (即 -9223372036854775808l),那么 abs 函数将不会返回绝对值,而只会返回最小值。 在这种情况下,如果您的代码进一步使用此绝对值,则可能会出现问题。
I needed the absolute value of a long , and looked deeply into Math.abs and found that if my argument is less than LONG.MIN_VAL which is -9223372036854775808l, then the abs function would not return an absolute value but only the minimum value. Inthis case if your code is using this abs value further then there might be an issue.
你能试试这个吗?
Can you please try this one?
在 for 循环中尝试一下:
Try this in the for loop:
在 kotlin 中,您可以使用 unaryPlus
https://kotlinlang .org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
In kotlin you can use unaryPlus
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
不要这样做
number = (number < 0 ? -number : number);
或者
如果 (number < 0) number = -number;
当您在代码上运行 find bug 时,这将是一个错误,它将报告为 RV_NEGATING_RESULT_OF
dont do this
number = (number < 0 ? -number : number);
or
if (number < 0) number = -number;
this will be an bug when you run find bug on your code it will report it as RV_NEGATING_RESULT_OF
只需调用 Math.abs。 例如:
这会将
x
设置为5
。请注意,如果您传递
Integer.MIN_VALUE
,则将返回相同的值(仍然是负数),因为int
的范围不允许表示正数等价物。Just call Math.abs. For example:
Which will set
x
to5
.Note that if you pass
Integer.MIN_VALUE
, the same value (still negative) will be returned, as the range ofint
does not allow the positive equivalent to be represented.您描述的概念称为“绝对值”,Java 有一个名为 Math.abs 为您做这件事。 或者您可以避免函数调用并自己完成:
或
The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:
or
你正在寻找绝对价值,伙计。
Math.abs(-5)
返回 5...You're looking for absolute value, mate.
Math.abs(-5)
returns 5...使用
abs
函数:Use the
abs
function:试试这个( x 前面的负数是有效的,因为它是一元运算符,查找更多 此处):
通过此功能,您可以将积极的因素转化为消极的因素,将消极的因素转化为积极的因素。
但是,如果您只想将负数变为正数,请尝试以下操作:
一个很酷的数学技巧! 对数字进行平方将保证 x^2 为正值,并且然后,开平方即可得到 x 的绝对值:
希望有帮助! 祝你好运!
Try this (the negative in front of the x is valid since it is a unary operator, find more here):
With this, you can turn a positive to a negative and a negative to a positive.
However, if you want to only make a negative number positive then try this:
A little cool math trick! Squaring the number will guarantee a positive value of x^2, and then, taking the square root will get you to the absolute value of x:
Hope it helps! Good Luck!
你问的是绝对值吗?
Math.abs(...) 是您可能想要的函数。
Are you asking about absolute values?
Math.abs(...) is the function you probably want.
您希望将每个数字包装到 Math.abs() 中。 例如
打印出“1”。
如果您想避免编写
Math.
部分,您可以静态包含 Math 实用程序。 只需与您的导入一起编写,您就可以通过编写来引用
abs()
函数You want to wrap each number into
Math.abs()
. e.g.prints out "1".
If you want to avoid writing the
Math.
-part, you can include the Math util statically. Just writealong with your imports, and you can refer to the
abs()
-function just by writing最简单但又冗长的方法是将每个数字包装在 Math.abs() 调用中,因此您可以添加:
进行逻辑更改以反映代码的结构。 也许很冗长,但它可以满足您的要求。
The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:
with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.