C# 控制台输出格式

本文关键字:格式 输出 控制台 | 更新日期: 2023-09-27 18:36:42

我正在尝试显示一个阶乘,例如(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;
}

谢谢!

C# 控制台输出格式

问题是你的 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 时不再存在于作用域中。

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

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

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();
}

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

此外,您可能想要除整数之外的其他内容。 阶乘变得非常大非常快 - 任何超过 16 都会返回错误的结果。