Is minus zero (-0) equivalent to zero (0) in C#

后端 未结 3 939
情歌与酒
情歌与酒 2020-12-18 18:13

Is minus zero (-0) equivalent to zero (0) in C#?

3条回答
  •  抹茶落季
    2020-12-18 18:34

    For integers, there is no binary representation that makes a difference between 0 and -0, so they are by definition equal.

    For IEEE floating-point numbers, there is a distinction of negative and positive zero. I made some tests (CLR of .NET Framework 2.0, C# 3) and it seems that they are considered equal, which is actually the behavior expected according to the IEEE 754 standard.

    Here's my test code to show that:

        double minusOne = -1.0;
        double positiveZero = 0.0;
        double negativeZero = minusOne*positiveZero;
        Console.WriteLine("{0} == {1} -> {2}", positiveZero, negativeZero, positiveZero == negativeZero);
        Console.WriteLine("Binary representation is equal: {0}", BitConverter.DoubleToInt64Bits(positiveZero) == BitConverter.DoubleToInt64Bits(negativeZero));
    

    Returns:

    0 == 0 -> True
    Binary representation is equal: False
    

提交回复
热议问题