写出n!的算法
C#
递归方式:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("请输入一个数!"); 6 int input =Convert.ToInt32(Console.ReadLine()); 7 int result= GetFactorialValue(input); 8 Console.WriteLine("{0}的阶乘的值是:{1}", input, result); 9 Console.ReadKey(); 10 } 11 /// <summary> 12 /// 获得阶乘的值 13 /// </summary> 14 /// <param name="input"></param> 15 /// <returns></returns> 16 private static int GetFactorialValue(int input) 17 { 18 if (input == 0 || input == 1) 19 { 20 return 1; 21 } 22 return input*GetFactorialValue(input - 1); 23 } 24 }
for循环方式:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("请输入一个数!"); 6 int input =Convert.ToInt32(Console.ReadLine()); 7 //int result= GetFactorialValue(input); 8 int result = GetFact(input); 9 Console.WriteLine("{0}的阶乘的值是:{1}", input, result); 10 Console.ReadKey(); 11 } 12 private static int GetFact(int n) 13 { 14 int result = 1; 15 if (n <= 0) 16 { 17 result = 0; 18 19 } 20 for (int i = n; i > 0; i--) 21 { 22 result = result * i; 23 } 24 return result; 25 } 26 }
研究中.....
会的就在评论吧,欢迎你们的参与,谢谢!