【发布时间】:2010-11-04 17:23:49
【问题描述】:
如何在 C# 中检查数字是正数还是负数?
【问题讨论】:
-
有用的问题。
标签: c#
如何在 C# 中检查数字是正数还是负数?
【问题讨论】:
标签: c#
bool positive = number > 0;
bool negative = number < 0;
【讨论】:
当然,实际上没有人给出正确答案,
num != 0 // num is positive *or* negative!
【讨论】:
is positive or is negative不是is (positive or negative)
杀戮!
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);
}
}
【讨论】:
SignDeterminatorFactory 实例化一个实现ISignDeterminator 的类。
int?!你在 C# 的哪个神奇领域工作?
IsImaginary。
Math.Sign method 是一种方法。它将返回 -1 用于负数,1 用于正数,0 用于等于零的值(即零没有符号)。如果双精度和单精度变量等于 NaN,则会引发异常 (ArithmeticException)。
【讨论】:
Math.Sign 的返回值进行相等比较(因为它明确定义了可能的返回值。)
num < 0 // number is negative
【讨论】:
这是行业标准:
int is_negative(float num)
{
char *p = (char*) malloc(20);
sprintf(p, "%f", num);
return p[0] == '-';
}
【讨论】:
你们这些年轻人和你们喜欢的小于号。
在我以前,我们不得不使用Math.abs(num) != num //number is negative!
【讨论】:
Int16、Int32、Int64),如果num 是MinValue,它都会抛出OverflowException。浮点值的结果更糟,它们也可能是NaN,因为NaN != NaN。
public static bool IsPositive<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) > 0;
}
【讨论】:
本地程序员的版本。小端系统的行为是正确的。
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;
}
永远不要使用它。
【讨论】:
IsPositiveChecker、IsPositiveCheckerInterface、IsPositiveCheckerFactory 和IsPositiveCheckerFactoryInterface。
result = (Marshal.ReadByte(memory, 3) & 0x80) == 0;。此外,您应该在最后的某处有一个return result;,这样它实际上会返回结果。
if (num < 0) {
//negative
}
if (num > 0) {
//positive
}
if (num == 0) {
//neither positive or negative,
}
或者使用“else ifs”
【讨论】:
对于 32 位有符号整数,例如 System.Int32,在 C# 中又名 int:
bool isNegative = (num & (1 << 31)) != 0;
【讨论】:
你只需要比较值和它的绝对值是否相等:
if (value == Math.abs(value))
return "Positif"
else return "Negatif"
【讨论】:
bool isNegative(int n) {
int i;
for (i = 0; i <= Int32.MaxValue; i++) {
if (n == i)
return false;
}
return true;
}
【讨论】:
public static bool IsNegative<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) < 0;
}
【讨论】:
int j = num * -1;
if (j - num == j)
{
// Num is equal to zero
}
else if (j < i)
{
// Num is positive
}
else if (j > i)
{
// Num is negative
}
【讨论】:
此代码利用 SIMD 指令来提高性能。
public static bool IsPositive(int n)
{
var v = new Vector<int>(n);
var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
return result;
}
【讨论】:
第一个参数存储在 EAX 寄存器和结果中。
function IsNegative(ANum: Integer): LongBool; assembler;
asm
and eax, $80000000
end;
【讨论】: