我如何检查一个数字是正的或负的c# ?
当前回答
if (num < 0) {
//negative
}
if (num > 0) {
//positive
}
if (num == 0) {
//neither positive or negative,
}
或者使用else if
其他回答
本地程序员版本。行为对于小端系统是正确的。
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;
}
永远不要用这个。
bool positive = number > 0;
bool negative = number < 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
}
你只需要比较是否值和它的绝对值相等:
if (value == Math.abs(value))
return "Positif"
else return "Negatif"
过分了!
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);
}
}
推荐文章
- c# XML文档网站链接
- 如何从日期时间获得完整的月份名称
- 在c#中创建一个对象的副本
- 通过字符串获取c#动态属性的值
- 我如何检查一个数字是正的或负的c# ?
- 无法找到testhost.dll。请发布测试项目并重试
- 什么是indexoutofraneexception / argumentoutofraneexception,我如何修复它?
- DbEntityValidationException -我如何容易地告诉是什么导致了错误?
- 嵌套等待平行。ForEach
- 我如何执行插入和返回插入的身份与Dapper?
- 如何从c#窗体返回一个值?
- 转换JSON字符串到c#对象
- Try /catch +使用,语法正确
- 在using块的中间返回
- 找到未使用的代码