Create a factorial program that returns an error indication when something goes wrong. - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Factorial

Description

Create a factorial program that returns an error indication when something goes wrong.

Demo Code

using System;/*from w  w  w . j a va2  s.  c o m*/
public class MyMathFunctions
{
   public const int NEGATIVE_NUMBER = -1;
   public const int NON_INTEGER_VALUE = -2;
   public static double Factorial(double value)
   {
      if (value < 0)
      {
         return NEGATIVE_NUMBER;
      }
      int valueAsInt = (int)value;
      if (valueAsInt != value)
      {
         return NON_INTEGER_VALUE;
      }
      double factorial = 1.0;
      do
      {
         factorial *= value;
         value -= 1.0;
      } while (value > 1);
      return factorial;
   }
}
public class Program
{
   public static void Main(string[] args)
   {
      for (int i = 6; i > -6; i--)
      {
         double factorial = MyMathFunctions.Factorial(i);
         if (factorial == MyMathFunctions.NEGATIVE_NUMBER)
         {
            Console.WriteLine("Factorial() passed a negative number");
            break;
         }
         if (factorial == MyMathFunctions.NON_INTEGER_VALUE)
         {
            Console.WriteLine("Factorial() passed a non-integer number");
            break;
         }
         Console.WriteLine("i = {0}, factorial = {1}", i, factorial);
      }
   }
}

Result


Related Tutorials