查找Double/Float值为奇数或偶数在C#中

Rav*_*ddy -3 c# double

如何在没有将它们转换为C#的情况下查找double值是偶数还是奇数int?例如

123.0d     - odd
456.0d     - even
3.1415926d - floating point (neither odd nor even)
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 6

尝试模%运算符:

 double x = 123;

 string result = x % 2 == 0 
    ? "even" : x % 2 == 1 || x % 2 == -1
    ? "odd"
    : "floating point"; // e.g. 123.456789
Run Code Online (Sandbox Code Playgroud)

编辑:什么时候有效?浮点值(single,double)不包含指数部分时精确表示(整数)值.

https://en.wikipedia.org/wiki/Single-precision_floating-point_format https://en.wikipedia.org/wiki/Double-precision_floating-point_format

因此,无论何时x在这些范围内,解决方案都能正常运行

[-2**24..2**24] == [-16777216..16777216]                 (float)
[-2**52..2**52] == [-4503599627370496..4503599627370496] (double)
Run Code Online (Sandbox Code Playgroud)

请注意,因为.Net认为negative % positive == nonpostive,例如-3 % 2 == -1我们必须检查 x % 2 == -1以及x % 2 == 1