Floating-point types have special values to deal with the results of certain operations.
These special values are
The float and double types have constants for NaN, +Infinity, and -Infinity.
The constants that represent special values for double and float are as follows:
Special value | Double constant | Float constant |
---|---|---|
NaN | double.NaN | float.NaN |
+Infinity | double.PositiveInfinity | float.PositiveInfinity |
-Infinity | double.NegativeInfinity | float.NegativeInfinity |
-0 | -0.0 | -0.0f |
For example, you can output the value of Negative Infinity in double:
Console.WriteLine (double.NegativeInfinity); // -Infinity
Dividing a nonzero number by zero results in an infinite value.
Dividing zero by zero, or subtracting infinity from infinity, results in a NaN.
When using ==, a NaN value is never equal to another value, even another NaN value.
To test whether a value is NaN, you must use the float.IsNaN or double.IsNaN method.
When using object.Equals, two NaN values are equal.
using System; class MainClass/*from w ww . j a va 2s . co m*/ { public static void Main(string[] args) { Console.WriteLine ( 1.0 / 0.0); // Infinity Console.WriteLine (-1.0 / 0.0); // -Infinity Console.WriteLine ( 1.0 / -0.0); // -Infinity Console.WriteLine (-1.0 / -0.0); // Infinity Console.WriteLine ( 0.0 / 0.0); // NaN Console.WriteLine ((1.0 / 0.0) - (1.0 / 0.0)); // NaN Console.WriteLine (0.0 / 0.0 == double.NaN); // False Console.WriteLine (double.IsNaN (0.0 / 0.0)); // True Console.WriteLine (object.Equals (0.0 / 0.0, double.NaN)); // True } }