• Top Posts

    C# dotnet Create a factorial program that returns an error indication when something goes wrong


      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 Program1  
       {  
         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);  
             Console.ReadLine();  
           }  
         }  
       }  
    

    No comments

    Post Top Ad

    ad728

    Post Bottom Ad

    ad728