Translate

Thursday, July 4, 2013

c# check divide by zero

In C# if the type is float or double, divide by zero does NOT throw an exception. Dividing by zero results in Infinity (positive or negative) Or Not a Number.

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var k = 1f / 0f;
            Console.WriteLine(k);// Displays Infinity
            if(float.IsPositiveInfinity(k))
            {
                Console.WriteLine("Positive infinity");//code enters here
            }

            var z = 0f / 0f;
            Console.WriteLine(z);//Displays NaN
            if(float.IsNaN(z))
            {
                Console.WriteLine("Not a Number");//code enters here
            }

        }
    }
}



No comments:

Post a Comment

Comments will appear once they have been approved by the moderator