我有这段代码,它从用户那里获取输入并计算其阶乘和小于输入数字的阶乘,但我一直只获取第一个数字的阶乘,其余为 0。它应该是这样的:例如,如果输入为 5:
5! = 120
4! = 24
3! = 6
2! = 4
1! = 1
如何让循环遍历输入数字下面的所有数字?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace multiple_factorials
{
class Program
{
static void Main(string[] args)
{
int num, n;
Console.WriteLine(".....................[Application 1].....................\n\n");
Console.WriteLine("Please enter a number to get its factorial: ");
num = Convert.ToInt32(Console.ReadLine());
n = num; // Assign n to num
while (num > 0)
{
for (int i = n - 1; i > 0; i--)
{
n *= i;
}
Console.WriteLine("Factorial of {0}! = {1}\n", num, n);
num--;
}
}
}
}
你已经包括了System.Linq
所以我提出了一个 LINQ 解决方案:
int n = 5;
// result == 120
int result = Enumerable.Range(1, n).Aggregate(1, (p, item) => p * item);
然而,LINQ 是overkill这里,以及for loop更具可读性。要打印出所有行:
int num = 5;
String result = String.Join(Environment.NewLine,
Enumerable.Range(1, num)
.Reverse()
.Select((index) =>
String.Format("Factorial of {0}! = {1}\n",
index,
Enumerable.Range(1, index).Aggregate(1, (p, item) => p * item))));
Console.Write(result);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)