将负数变为正数

发布于 2024-07-13 02:51:18 字数 121 浏览 9 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

时光与爱终年不遇 2024-07-20 02:51:19

当您需要表示一个没有损失或缺失(负值)概念的值时,这称为“绝对值”。


获取绝对值的逻辑非常简单:“如果是正数,则维持它。如果是负数,则取反”


这意味着您的逻辑和代码应如下所示工作:

//If value is negative...
if ( value < 0 ) {
  //...negate it (make it a negative negative-value, thus a positive value).
  value = negate(value);
}

有 2 种方法可以对某个值取反:

  1. 通过对它的值取反:value = (-value);
  2. 通过将其相乘通过“100% 负”或“-1”:值 = 值 *
    (-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));


考虑到这一点,并考虑具有总和的情况对于像您这样的多个数字,实现一个函数是一个好主意:

int getSumOfAllAbsolutes(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += Math.abs(values[i]);
  }
  return total;
}

根据您可能再次需要相关代码的可能性,将它们添加到您自己的“utils”库中,拆分这些函数也可能是一个好主意首先进入它们的核心组件,并将最终函数简单地维护为对核心组件现在拆分的函数的调用嵌套:

int[] makeAllAbsolute(int[] values){
  //@TIP: You can also make a reference-based version of this function, so that allocating 'absolutes[]' is not needed, thus optimizing.
  int[] absolutes = values.clone();
  for(int i=0; i<values.lenght; i++){
    absolutes[i] = Math.abs(values[i]);
  }
  return absolutes;
}

int getSumOfAllValues(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += values[i];
  }
return total;
}

int getSumOfAllAbsolutes(int[] values){
  return getSumOfAllValues(makeAllAbsolute(values));
}

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:

//If value is negative...
if ( value < 0 ) {
  //...negate it (make it a negative negative-value, thus a positive value).
  value = negate(value);
}

There are 2 ways you can negate a value:

  1. By, well, negating it's value: value = (-value);
  2. By multiplying it by "100% negative", or "-1": 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 actually value = 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 provided Math.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:

int getSumOfAllAbsolutes(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += Math.abs(values[i]);
  }
  return total;
}

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:

int[] makeAllAbsolute(int[] values){
  //@TIP: You can also make a reference-based version of this function, so that allocating 'absolutes[]' is not needed, thus optimizing.
  int[] absolutes = values.clone();
  for(int i=0; i<values.lenght; i++){
    absolutes[i] = Math.abs(values[i]);
  }
  return absolutes;
}

int getSumOfAllValues(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += values[i];
  }
return total;
}

int getSumOfAllAbsolutes(int[] values){
  return getSumOfAllValues(makeAllAbsolute(values));
}
他不在意 2024-07-20 02:51:19

为什么不将该数字乘以-1

像这样:

//Given x as the number, if x is less than 0, return 0 - x, otherwise return x:
return (x <= 0.0F) ? 0.0F - x : x;

Why don't you multiply that number with -1?

Like This:

//Given x as the number, if x is less than 0, return 0 - x, otherwise return x:
return (x <= 0.0F) ? 0.0F - x : x;
橙幽之幻 2024-07-20 02:51:19

如果您对二进制补码的机制感兴趣,下面是绝对低效但具有说明性的低级方法:

private static int makeAbsolute(int number){
     if(number >=0){
        return number;
     } else{
        return (~number)+1;
     }
}

If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:

private static int makeAbsolute(int number){
     if(number >=0){
        return number;
     } else{
        return (~number)+1;
     }
}
变身佩奇 2024-07-20 02:51:19

可以使用库函数Math.abs()
Math.abs() 返回参数的绝对值

  • 如果参数为负数,则返回参数的否定值。
  • 如果参数为正,则按原样返回数字。

例如:

  1. int x=-5;
    System.out.println(Math.abs(x));

输出:5

  1. 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 argument

  • if the argument is negative, it returns the negation of the argument.
  • if the argument is positive, it returns the number as it is.

e.g:

  1. int x=-5;
    System.out.println(Math.abs(x));

Output: 5

  1. int y=6;
    System.out.println(Math.abs(y));

Output: 6

冷…雨湿花 2024-07-20 02:51:19
String s = "-1139627840";
BigInteger bg1 = new BigInteger(s);
System.out.println(bg1.abs());

或者:

int i = -123;
System.out.println(Math.abs(i));
String s = "-1139627840";
BigInteger bg1 = new BigInteger(s);
System.out.println(bg1.abs());

Alternatively:

int i = -123;
System.out.println(Math.abs(i));
情域 2024-07-20 02:51:19

要将负数转换为正数(这称为绝对值),请使用 Math.abs()。 Math.abs() 方法的工作原理如下

“number = (number < 0 ? -number : number);”。

在下面的示例中,Math.abs(- 1) 将负数 1 转换为正数 1。

示例

public static void main(String[] args) {

    int total = 1 + 1 + 1 + 1 + (-1);
    
    //output 3
    System.out.println("Total : " + total);
    
    int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);
    
    //output 5
    System.out.println("Total 2 (absolute value) : " + total2);
    
}

输出

总数:3
总计2(绝对值):5

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.

example

public static void main(String[] args) {

    int total = 1 + 1 + 1 + 1 + (-1);
    
    //output 3
    System.out.println("Total : " + total);
    
    int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);
    
    //output 5
    System.out.println("Total 2 (absolute value) : " + total2);
    
}

Output

Total : 3
Total 2 (absolute value) : 5

婴鹅 2024-07-20 02:51:19

我会推荐以下解决方案:

不使用 lib fun:

    value = (value*value)/value

(上述内容实际上不起作用。)

使用 lib fun:

   value = Math.abs(value);

I would recommend the following solutions:

without lib fun:

    value = (value*value)/value

(The above does not actually work.)

with lib fun:

   value = Math.abs(value);
送君千里 2024-07-20 02:51:19

我看到人们在说 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.

趴在窗边数星星i 2024-07-20 02:51:19

我需要 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.

变身佩奇 2024-07-20 02:51:19

你能试试这个吗?

public static int toPositive(int number) {
    return number & 0x7fffffff;
}

Can you please try this one?

public static int toPositive(int number) {
    return number & 0x7fffffff;
}
请叫√我孤独 2024-07-20 02:51:19
if(arr[i]<0)

Math.abs(arr[i]);  //1st way (taking absolute value)

arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)

arr[i]= ~(arr[i]-1);   //3rd way (taking negation)
if(arr[i]<0)

Math.abs(arr[i]);  //1st way (taking absolute value)

arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)

arr[i]= ~(arr[i]-1);   //3rd way (taking negation)
甜点 2024-07-20 02:51:19

在 for 循环中尝试一下:

sum += Math.abs(arr[i])

Try this in the for loop:

sum += Math.abs(arr[i])
七度光 2024-07-20 02:51:19

在 kotlin 中,您可以使用 unaryPlus

input = input.unaryPlus()

https://kotlinlang .org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html

In kotlin you can use unaryPlus

input = input.unaryPlus()

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html

少年亿悲伤 2024-07-20 02:51:19

不要这样做

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

决绝 2024-07-20 02:51:18

只需调用 Math.abs。 例如:

int x = Math.abs(-5);

这会将 x 设置为 5

请注意,如果您传递 Integer.MIN_VALUE,则将返回相同的值(仍然是负数),因为 int 的范围不允许表示正数等价物。

Just call Math.abs. For example:

int x = Math.abs(-5);

Which will set x to 5.

Note that if you pass Integer.MIN_VALUE, the same value (still negative) will be returned, as the range of int does not allow the positive equivalent to be represented.

公布 2024-07-20 02:51:18

您描述的概念称为“绝对值”,Java 有一个名为 Math.abs 为您做这件事。 或者您可以避免函数调用并自己完成:

number = (number < 0 ? -number : number);

if (number < 0)
    number = -number;

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:

number = (number < 0 ? -number : number);

or

if (number < 0)
    number = -number;
葬﹪忆之殇 2024-07-20 02:51:18

你正在寻找绝对价值,伙计。 Math.abs(-5) 返回 5...

You're looking for absolute value, mate. Math.abs(-5) returns 5...

温柔戏命师 2024-07-20 02:51:18

使用 abs 函数:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);

Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);
夏日浅笑〃 2024-07-20 02:51:18

试试这个( x 前面的负数是有效的,因为它是一元运算符,查找更多 此处):

int answer = -x;

通过此功能,您可以将积极的因素转化为消极的因素,将消极的因素转化为积极的因素。


但是,如果您只想将负数变为正数,请尝试以下操作:

int answer = Math.abs(x);

一个很酷的数学技巧! 对数字进行平方将保证 x^2 为正值,并且然后,开平方即可得到 x 的绝对值:

int answer = Math.sqrt(Math.pow(x, 2));

希望有帮助! 祝你好运!

Try this (the negative in front of the x is valid since it is a unary operator, find more here):

int answer = -x;

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:

int answer = Math.abs(x);

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:

int answer = Math.sqrt(Math.pow(x, 2));

Hope it helps! Good Luck!

香橙ぽ 2024-07-20 02:51:18

对于正数调用此代码安全。

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20

This code is not safe to be called on positive numbers.

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20
你对谁都笑 2024-07-20 02:51:18

你问的是绝对值吗?

Math.abs(...) 是您可能想要的函数。

Are you asking about absolute values?

Math.abs(...) is the function you probably want.

霞映澄塘 2024-07-20 02:51:18

您希望将每个数字包装到 Math.abs() 中。 例如

System.out.println(Math.abs(-1));

打印出“1”。

如果您想避免编写 Math. 部分,您可以静态包含 Math 实用程序。 只需与您的导入一起编写

import static java.lang.Math.abs;

,您就可以通过编写来引用 abs() 函数

System.out.println(abs(-1));

You want to wrap each number into Math.abs(). e.g.

System.out.println(Math.abs(-1));

prints out "1".

If you want to avoid writing the Math.-part, you can include the Math util statically. Just write

import static java.lang.Math.abs;

along with your imports, and you can refer to the abs()-function just by writing

System.out.println(abs(-1));
非要怀念 2024-07-20 02:51:18

最简单但又冗长的方法是将每个数字包装在 Math.abs() 调用中,因此您可以添加:

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

进行逻辑更改以反映代码的结构。 也许很冗长,但它可以满足您的要求。

The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:

Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)

with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文