¿Cómo verifico si un número es positivo o negativo en C #?
¿Cómo verifico si un número es positivo o negativo en C #?
Respuestas:
bool positive = number > 0;
bool negative = number < 0;
Por supuesto, nadie ha dado la respuesta correcta,
num != 0 // num is positive *or* negative!
is positive or is negativenois (positive or negative)
OVERKILL!
public static class AwesomeExtensions
{
public static bool IsPositive(this int number)
{
return number > 0;
}
public static bool IsNegative(this int number)
{
return number < 0;
}
public static bool IsZero(this int number)
{
return number == 0;
}
public static bool IsAwesome(this int number)
{
return IsNegative(number) && IsPositive(number) && IsZero(number);
}
}
ISignDeterminatorusando a SignDeterminatorFactory.
int?! ¿En qué tierra mágica de C # estás trabajando?
IsImaginary.
El método Math.Sign es un camino a seguir. Devolverá -1 para números negativos, 1 para números positivos y 0 para valores iguales a cero (es decir, cero no tiene signo). Las variables de precisión doble y única provocarán una excepción ( ArithmeticException ) si son iguales a NaN.
Math.Sign(ya que define explícitamente los posibles valores de retorno)
num < 0 // number is negative
Este es el estándar de la industria:
int is_negative(float num)
{
char *p = (char*) malloc(20);
sprintf(p, "%f", num);
return p[0] == '-';
}
Ustedes, jóvenes, y su fantasía, menos que signos.
¡En mi día tuvimos que usar Math.abs(num) != num //number is negative!
OverflowExceptionsi numes MinValuepor cualquier tipo se pasa en ( Int16, Int32, Int64). Los resultados son aún peores para los valores de coma flotante, donde también podrían estar NaN, desde entonces NaN != NaN.
public static bool IsPositive<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) > 0;
}
Versión del programador nativo. El comportamiento es correcto para los sistemas little-endian.
bool IsPositive(int number)
{
bool result = false;
IntPtr memory = IntPtr.Zero;
try
{
memory = Marshal.AllocHGlobal(4);
if (memory == IntPtr.Zero)
throw new OutOfMemoryException();
Marshal.WriteInt32(memory, number);
result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;
}
finally
{
if (memory != IntPtr.Zero)
Marshal.FreeHGlobal(memory);
}
return result;
}
Nunca uses esto.
IsPositiveChecker, IsPositiveCheckerInterface, IsPositiveCheckerFactory, y IsPositiveCheckerFactoryInterface, sin embargo.
result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;. Además, debe tener un return result;lugar allí al final para que realmente devuelva el resultado.
if (num < 0) {
//negative
}
if (num > 0) {
//positive
}
if (num == 0) {
//neither positive or negative,
}
o use "else ifs"
Para un entero con signo de 32 bits, como System.Int32, también conocido inten C #:
bool isNegative = (num & (1 << 31)) != 0;
Solo tiene que comparar si el valor y su valor absoluto son iguales:
if (value == Math.abs(value))
return "Positif"
else return "Negatif"
El primer parámetro se almacena en el registro EAX y el resultado también.
function IsNegative(ANum: Integer): LongBool; assembler;
asm
and eax, $80000000
end;