C#浮动到双倍

0 c# floating-point double

static void Main(string[] args)
{
           double y = 23.12F;
           Console.WriteLine(y);
           Console.Read();
}
Run Code Online (Sandbox Code Playgroud)

为什么y的值显示23.1200008392334而不是23.12

static void Main(string[] args)
    {
        int i = -9; uint j = (uint)i;
        Console.WriteLine(j);
        Console.Read();
    }
Run Code Online (Sandbox Code Playgroud)

j如何显示值4294967287

Mar*_*ell 7

浮点只能保证精确到整数值; 除此之外,它们不能代表所有数字; 由于IEEE754的工作原理,23.1200008392334是最接近23.12的.

如果你想要"典型"处理十进制值...请decimal改用:

decimal y = 23.12M;
Run Code Online (Sandbox Code Playgroud)

随着uint- 因为uint没有负值.相反,您正在从最大值向后追踪uint.如果您不想这样,请使用checked:

uint j = checked((uint) i);
Run Code Online (Sandbox Code Playgroud)

要么

checked
{
    uint j = (uint)i;
}
Run Code Online (Sandbox Code Playgroud)

然后它会在一阵火花中爆炸而不是爆炸.有时是好事; 有时候很糟糕 unchecked是默认值.