0

我试图让一个阶乘显示为例如(5的阶乘是5 * 4 * 3 * 2 * 1)

我正在使用阶乘方法,但它不接受Console.Write(i + " x ");我的代码中的行。

任何帮助都会很棒。这是我的代码。

//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
    string number_str;
    double factorial = 1;

    Console.WriteLine("Please enter number");
    number_str = Console.ReadLine();

    int num = Convert.ToInt32(number_str);

    // If statement is used so when the user inputs 0, INVALID is outputed
    if (num <= 0)
    {
        Console.WriteLine("You have entered an invalid option");
        Console.WriteLine("Please enter a number");
        number_str = Console.ReadLine();

        num = Convert.ToInt32(number_str);
        //Console.Clear();
        //topmenu();
        //number_str = Console.ReadLine();
    }

    if (num >= 0)
    {
        while (num != 0) 
        {
            for (int i = num; i >= 1; i--)
            {
                factorial = factorial * i;
            }
            Console.Write(i + " x ");

            Console.Clear();
            Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
            factorial = 1;
            Console.WriteLine("(please any key to return to main menu)");
            Console.ReadKey();
            Console.Clear();
            topmenu();
        }
    }

    return factorial;
}

谢谢!

4

2 回答 2

5

问题是你的 for 循环没有使用大括号,所以范围只有一行。

尝试适当地添加大括号:

for (int i = num; i >= 1; i--)
{
    factorial = factorial * i;
    Console.Write(i.ToString() + " x ");
}

Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);    

没有大括号,该i变量仅存在于下一条语句 ( factorial = factorial * i;) 中,并且在您调用 时不再存在于范围内Console.Write

您可能还希望Console.Clear立即删除对 this的调用Write,否则您将看不到它。

于 2013-10-24T17:38:46.200 回答
1

这是一个需要考虑的解决方案

public static void Main()
{
    Console.WriteLine("Please enter number");

    int input;
    while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
    {
        Console.WriteLine("You have enter an invald option");
        Console.WriteLine("Please enter number");
    }

    Console.Write("Factorial of " + input + " is : ");

    int output = 1;
    for (int i = input; i > 0; i--)
    {
        Console.Write((i == input) ? i.ToString() : "*" + i);
        output *= i;
    }
    Console.Write(" = " +output);
    Console.ReadLine();
}

int.TryParse() 将对您有益,因此如果用户输入非整数,程序不会崩溃

此外,您可能还需要整数以外的东西。阶乘变得非常大非常快 - 任何超过 16 的东西都会返回错误的结果。

于 2013-10-24T17:46:47.237 回答