在c#中使用带有阶乘的while循环

时间:2014-10-06 23:45:28

标签: c#

我正在社区大学参加计算机编程课程,教师希望我们一会儿看一下显示数字7的阶乘。我把下面的代码编写为

using System;
namespace TheLoop
{
    class TheLoop
    {
        static void Main(string[] args)
        {
            int number = 7;  
            long factorial = number;
            while (number > 1)
                factorial *= --number;
            System.Console.WriteLine(factorial);
            Console.ReadKey();

        }
    }
}

代码工作正常。但是教练希望我们显示循环的每一步,例如

1.  7 * 6 = 42
2.  42 * 5 = 210
3.  210 * 4 = 840
4.  840 * 3 = 2520
5.  2520 * 2 = 5040

and so on, other than just displaying the result
抱歉,我是C#的新手可以有人告诉我该怎么做吗?

3 个答案:

答案 0 :(得分:2)

在您的while内,您可以同时访问当前号码和当前因子,如下所示:

while (number > 1)
{
    // Print a Console.WriteLine() in here with what you want
    factorial *= --number;
}

答案 1 :(得分:-2)

这个怎么样:

int number = 7;  
int i = 1;
long factorial = number;
while (number > 1)
{
    factorial *= --number;
    Console.WriteLine("{0}. {1} * {2} = {3}", i++, factorial/number, number, factorial);
}
Console.WriteLine(factorial);

答案 2 :(得分:-5)

System.Console.WriteLine(number +" *" + --number +" =" + factorial);

这有用吗?