在c#中使用带阶乘的while循环
本文关键字:阶乘 while 循环 | 更新日期: 2023-09-27 18:25:54
我正在一所社区大学上计算机编程课,老师希望我们花点时间来显示数字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#的新手,有人能教我怎么做吗?
在while
中,您可以访问当前数字和当前阶乘,因此如下所示:
while (number > 1)
{
// Print a Console.WriteLine() in here with what you want
factorial *= --number;
}
这个怎么样:
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);
System.Console.WriteLine(数字+"*"+-数字+"="+阶乘);
这行得通吗?