double a = 0 / 0d;
if (double.IsNaN(a)){ //do } 在浮點數計算中,
0除以0將得到NaN
,正數除以0將得到PositiveInfinity
,負數除以0將得到NegativeInfinity
。 浮點數運算從不引發異常。
C#語言中,對於 int,long 和 decimal類型的數,任何數除以 0 所得的結果是無窮大,不在int,long 和 decimal 類型的范圍之內,所以計算 6/0 之類的表達式會出錯。
但是,double 和 float 類型實際上有一個可以表示無窮大的特殊值:5.0/0.0 = Infinity (無窮大),這個規則唯一的例外是0.0/0.0 = NaN (Not a Number)。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Infinity_NaN 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Console.WriteLine("5 / 2 = {0}", 5 / 2); // 2 13 Console.WriteLine("5.0 / 2.0 = {0}", 5.0 / 2.0); // 2.5 14 Console.WriteLine("5.0 / 2 = {0}", 5.0 / 2); // 2.5 15 Console.WriteLine("5 / 2.0 = {0}", 5 / 2.0); // 2.5 16 Console.WriteLine("5.0 / 0.0 = {0}", 5.0 / 0.0); // Infinity 17 Console.WriteLine("5.0 / 0 = {0}", 5.0 / 0); // Infinity 18 Console.WriteLine("0.0 / 0.0 = {0}", 0.0 / 0.0); // NaN 19 Console.WriteLine("5 / 0.0 = {0}", 5 / 0.0); // Infinity 20 Console.WriteLine("0.0 / 0 = {0}", 0.0 / 0); // NaN 21 22 //Console.WriteLine("5 / 0 = {0}", 5 / 0); // Err: Division by constant zero 23 //Console.WriteLine("0 / 0 = {0}", 0 / 0); // Err: Division by constant zero 24 25 // Infinity + 10 = Infinity 26 // Infinity * 0 = 0 27 // NaN + 10 = NaN 28 // NaN * 0 = NaN 29 } 30 } 31 }