模数运算符中的C#Bug%

时间:2012-05-24 19:03:35

标签: c# .net math modulo

解决了一个问题我发现了一些有趣的发现。

此程序的结果

    static void Main(string[] args)
    {
        int i4 = 4;
        Console.WriteLine("int i4 = 4;");
        Console.WriteLine("i4 % 1 = {0}", i4 % 1);

        double d4 = 4.0;
        Console.WriteLine("double d4 = 4.0;");
        Console.WriteLine("d4 % 1 = {0}", d4 % 1);
        Console.WriteLine("-----------------------------------------------------------");
        int i64 = 64;
        double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0);
        Console.WriteLine("int i64 = 64;");
        Console.WriteLine("double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = {0}", dCubeRootOf64);
        Console.WriteLine("dCubeRootOf64 = {0}", dCubeRootOf64);
        Console.WriteLine("dCubeRootOf64 % 1 = {0} ??????????????  Why 1. ??????????", dCubeRootOf64 % 1);

        Console.ReadLine();
    }

int i4 = 4;
i4 % 1 = 0
double d4 = 4.0;
d4 % 1 = 0
-----------------------------------------------------------
int i64 = 64;
double dCubeRootOf64 = Math.Pow(i64, 1.0 / 3.0) = 4
dCubeRootOf64 = 4
dCubeRootOf64 % 1 = 1 ??????????????  Why 1. ??????????

int 4 % 1 = 0 - 正确

double 4.0 % 1 = 0 - 正确

但是错误在于:

Math.Pow(64,1.0 / 3.0)%1 = 1

64的立方体根是4.为什么在这种情况下4 % 1 = 1

2 个答案:

答案 0 :(得分:12)

Math.Pow(64, 1.0 / 3.0)返回3.9999999999999996 显示时,它会四舍五入为4

以模1为模可返回0.99999999999999956,在显示时同样四舍五入为1

您可以通过添加.ToString("R")

来查看真实值

答案 1 :(得分:3)

dCubeRootOf64 % 1 = 1返回1而不是0;因为Math.Pow(i64, 1.0 / 3.0)会返回3.99999999999999963.9999999999999996 % 1会返回0.99999999999999956,而{{1}}会返回到1。

因此结果为1。