Why is double.NaN not equal to itself?

后端 未结 11 1264
心在旅途
心在旅途 2020-11-27 17:42

Can someone explain this to me? In C# double.NaN is not equal to double.NaN

bool huh = double.NaN == double.NaN; // huh = false
bool huh2 = double.NaN >=          


        
11条回答
  •  抹茶落季
    2020-11-27 18:10

    The Equality operator considers two NaN values to be unequal to one another. In general, Double operators cannot be used to compare Double.NaN with other Double values, although comparison methods (such as Equals and CompareTo) can. see below examples

    Referenced from msdn

    class Program
    {
        static void Main(string[] args)
        {
            Double i = Double.NaN;
            while (!i.Equals(i)) //this would be result in false
            //while(i != i) // this would result in true.
            {
                Console.WriteLine("Hello");
            }
        }
    }
    

    here is .net fiddle for the same.

提交回复
热议问题