Hacer un número negativo positivo


Tengo un método Java en el que estoy sumando un conjunto de números. Sin embargo, quiero que cualquier número negativo sea tratado como positivo. Así (1)+(2)+(1)+(-1) debe ser igual a 5.

Estoy seguro de que hay una manera muy fácil de hacer esto - simplemente no sé cómo.

Author: Paolo Forgia, 2009-01-30

16 answers

Simplemente llama a Matemáticas.abs . Por ejemplo:

int x = Math.abs(-5);

Que pondrá x a 5.

 313
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-23 07:53:53

El concepto que está describiendo se llama "valor absoluto", y Java tiene una función llamada Math.abs para hacerlo por ti. O puede evitar la llamada a la función y hacerlo usted mismo:

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

O

if (number < 0)
    number = -number;
 91
Author: Paul Tomblin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:54:52

Estás buscando valor absoluto, amigo. Math.abs(-5) devuelve 5...

 17
Author: Hexagon Theory,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:25:43

Utilice la función abs:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);
 12
Author: jpalecek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:25:23

Este código es seguro para ser llamado en números positivos también.

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20
 10
Author: AZ_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 10:57:07

¿Estás preguntando por valores absolutos?

Math.abdominales(...) es la función que probablemente desee.

 6
Author: Uri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:25:14

Desea envolver cada número en Math.abs(). por ejemplo,

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

Imprime "1".

Si desea evitar escribir la parte Math., puede incluir las matemáticas util estáticamente. Solo escribe

import static java.lang.Math.abs;

Junto con sus importaciones, y puede hacer referencia a la función abs() - simplemente escribiendo

System.out.println(abs(-1));
 6
Author: Henrik Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:25:44

La forma más fácil, si detallada, de hacer esto es envolver cada número en una matemática.llamada abs (), por lo que añadirías:

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

Con cambios de lógica para reflejar cómo se estructura su código. Verboso, tal vez, pero hace lo que quieres.

 5
Author: Eddie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-29 21:25:41

Cuando se necesita representar un valor sin el concepto de pérdida o ausencia (valor negativo), se llama "valor absoluto".


La lógica para obtener el valor absoluto es muy simple: "If it's positive, maintain it. If it's negative, negate it".


Lo que esto significa es que su lógica y código deben funcionar de la siguiente manera:

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

Hay 2 maneras de negar un valor:

  1. Negando su valor: value = (-value);
  2. Multiplicándolo por "100% negativo", o "-1": value = value * (-1);

Ambas son en realidad dos caras de la misma moneda. Es solo que normalmente no recuerdas que value = (-value); es en realidad value = 1 * (-value);.


Bueno, en cuanto a cómo realmente lo haces en Java, es muy simple, porque Java ya proporciona una función para eso, en el Math class: value = Math.abs(value);

Sí, hacerlo sin Math.abs() es solo una línea de código con matemáticas muy simples, pero ¿por qué hacer que tu código se vea feo? Solo tiene que utilizar la función Math.abs() de Java! Proporcionan un ¡razón!

Si es absolutamente necesario omitir la función, puede usar value = (value < 0) ? (-value) : value;, que es simplemente una versión más compacta del código que mencioné en la sección logic (3rd), utilizando el operador ternario (? :).


Además, puede haber situaciones en las que desee representar siempre pérdida o ausencia dentro de una función que podría recibir valores positivos y negativos.

En lugar de hacer una comprobación complicada, simplemente puede obtener el absoluto valor, y negarlo: negativeValue = (-Math.abs(value));


Con eso en mente, y considerando un caso con una suma de múltiples números como el suyo, sería una buena idea implementar una función:

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

Dependiendo de la probabilidad de que necesite código relacionado de nuevo, también podría ser una buena idea agregarlos a su propia biblioteca "utils", dividiendo dichas funciones en sus componentes principales primero, y manteniendo la función final simplemente como un nido de llamadas a los componentes principales' ahora-dividir funciones:

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));
}
 5
Author: XenoRo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 21:59:36

¿por Qué no multiply that number with -1?

Así:

//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;
 3
Author: Muhammad Imran Tariq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-04 17:03:19

Sin lib fun:

    value = (value*value)/value

Con lib fun:

   value=Math.abs(value);
 3
Author: saidesh kilaru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-04 09:31:57

Prueba esto:

int answer = x * -1;

Con esto, puedes convertir un positivo en negativo y un negativo en positivo.

Espero que ayude! ¡Buena suerte!

 3
Author: Shreshth Kharbanda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-09 00:32:23

Si estás interesado en la mecánica del complemento de dos, aquí está la manera absolutamente ineficiente, pero ilustrativa de bajo nivel que se hace:

private static int makeAbsolute(int number){
     if(number >=0){
        return number;
     } else{
        return (~number)+1;
     }
}
 1
Author: Miquel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-16 18:20:59
String s = "-1139627840";
BigInteger bg1 = new BigInteger(s);
System.out.println(bg1.abs());

Alternativamente:

int i = -123;
System.out.println(Math.abs(i));
 1
Author: Ramkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-14 19:00:29

Necesitaba el valor absoluto de un largo , y miré profundamente en las matemáticas.abs y encontró que si mi argumento es menos que LARGO.MIN_VAL que es-9223372036854775808l, entonces la función abs no devolvería un valor absoluto sino solo el valor mínimo. En este caso, si su código está utilizando este valor abs más, entonces podría haber un problema.

 0
Author: Santhosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-24 16:53:04

No hagas esto

Number = (number

O

If (number

Esto será un error cuando ejecute find bug en su código, lo reportará como RV_NEGATING_RESULT_OF

 -3
Author: sai Gorantla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-05 19:08:04