Convertir a valor absoluto en Objective-C


¿Cómo convertir un número negativo a un valor absoluto en Objective-C?

Es decir,

-10

Se convierte en

10?

 176
Author: redconservatory, 2011-01-17

2 answers

Según el tipo de la variable, uno de abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), o fabsl(long double).

Esas funciones son parte de la biblioteca estándar de C, y por lo tanto están presentes tanto en Objective-C como en C simple (y están generalmente disponibles en programas de C++ también.)

(Por desgracia, no hay función habs(short). O scabs(signed char) para el caso...)


Los encabezados Objective-C de Apple y GNU también incluyen una macro ABS() que es independiente del tipo. No recomiendo usar ABS() sin embargo, ya que no se garantiza que sea seguro para los efectos secundarios. Por ejemplo, ABS(a++) tendrá un resultado indefinido.


Si está utilizando C++ o Objective-C++, puede traer el encabezado <cmath> y usar std::abs(), que está templada para todos los tipos de enteros y coma flotante estándar.

 442
Author: Jonathan Grynspan,
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-01-20 10:47:03

Puede usar esta función para obtener el valor absoluto:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}
 4
Author: da Rocha Pires,
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-05-26 09:42:02