如何查找double
值甚至或奇数而不将其转换为C#中的int
? E.g。
123.0d - odd
456.0d - even
3.1415926d - floating point (neither odd nor even)
答案 0 :(得分:6)
尝试模<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<def>
<svg id="thumb" width="100%" height="100%" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none"></path>
<path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"></path>
</svg>
</def>
</svg>
运算符:
%
修改:什么时候有效?浮点值( double x = 123;
string result = x % 2 == 0
? "even" : x % 2 == 1 || x % 2 == -1
? "odd"
: "floating point"; // e.g. 123.456789
,single
)如果不包含指数部分,则表示(整数)值正好。
https://en.wikipedia.org/wiki/Single-precision_floating-point_format https://en.wikipedia.org/wiki/Double-precision_floating-point_format
因此,只要double
在这些范围内
x
请注意,因为.Net假定[-2**24..2**24] == [-16777216..16777216] (float)
[-2**52..2**52] == [-4503599627370496..4503599627370496] (double)
,例如negative % positive == nonpostive
我们必须检查 -3 % 2 == -1
以及x % 2 == -1
答案 1 :(得分:0)
嗯,我认为你自己回答了你的问题,但这是我写的一个简短的代码:
static void Main(string[] args)
{
double number=10.0;
if(number%2==0)
{
Console.WriteLine("Your number is even!");
}
else
{
Console.WriteLine("Your number is odd!");
}
Console.ReadLine();
}
这种方式,如果它有效,你会看到非常好的
答案 2 :(得分:-1)
public static bool IsEven(double x)
{
return x % 2 == 0;
}
请注意,执行此操作需要更多代码来实现此操作,因此如果您将其置于生产环境中,则期望您的QA团队向您发送讨厌的电子邮件。
答案 3 :(得分:-2)
public bool isEven(double value)
{
decimal decVal = System.Convert.ToDecimal(value);
if (decVal % 2.0 == 0)
{
return true;
}
else
{
return false;
}
}
编辑:如果您先转换为小数,则应该有效。