C#计算阶乘 [英] C# to calculate factorial
本文介绍了C#计算阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码可以从用户那里获得输入,并计算出小于输入数字的阶乘和阶乘,但是我一直只获取第一个数字的阶乘,其余为0.应该像这样:例如,如果输入为5:
I have this code that gets an input from the user and calculate its factorial and the factorial for less than the input number, but I keep getting the factorial for the first number only and the rest is 0. It should be like this: For example, if the input is 5:
5!= 120
4!= 24
3!= 6
2!= 4
1!= 1
我如何让循环抛出所有输入数字以下的数字?
How do I make the loop go throw all the numbers below the input number?
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--;
}
}
}
}
推荐答案
只需在 while
循环内移动 n = num;
:
while (num > 0)
{
n = num;
for (int i = n - 1; i > 0; i--)
{
n *= i;
}
Console.WriteLine("Factorial of {0}! = {1}\n", num, n);
num--;
}
这篇关于C#计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文