c#-计算数字的阶乘

当我输入数字6以计算其阶乘时,它将返回30(这是错误的).

为什么我的程序产生不正确的输出?

using System;

namespace Scenario1_2
{
    class Program
    { 
        static void Main(string[] args)
        {
            int counter, number, fact;

            Console.WriteLine("Please enter the number you wish to factorize");
            number = int.Parse(Console.ReadLine());
            fact = number;

            for (counter = number - 1; counter >= 1; counter--)
            {
                fact = fact * counter;

                Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, fact);
                Console.ReadLine();
            }
        } 
    }
}
最佳答案
您看起来对编程还是C#还是陌生的,所以只是为了好玩,这会让您大吃一惊:

using System;

namespace Scenario1_2
{
    class Program
    { 
        static void Main(string[] args)
        {   
            Console.WriteLine("Please enter the number you wish to factorize");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
            Console.ReadKey(true);
        }

        static int Factorial(int n)
        {
           if (n >= 2) return n * Factorial(n - 1);
           return 1;
        } 
    }
}  

无循环,函数calls itself.

您也可以这样:

using System;

namespace Scenario1_2
{
    class Program
    { 
        static void Main(string[] args)
        {   
            Console.WriteLine("Please enter the number you wish to factorize");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorial(number));
            Console.ReadKey(true);
        }

        static int Factorial(int n)
        {
           return Enumerable.Range(1, n).Aggregate((i, r) => r * i);
        } 
    }
}

这真是一团糟:) …但是它确实将重要的工作简化为一行代码.

然后是我个人的最爱,无限枚举:

using System;

namespace Scenario1_2
{
    class Program
    { 
        static void Main(string[] args)
        {   
            Console.WriteLine("Please enter the number you wish to factorize");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("The number you entered was {0} and it's factorial is {1}", number, Factorials().Skip(number-1).First());
            Console.ReadKey(true);
        }

        static IEnumerable<int> Factorials()
        {
            int n = 1, f = 1;
            while (true) yield return f = f * n++;
        } 
    }
}

转载注明原文:c#-计算数字的阶乘 - 代码日志