簡體   English   中英

C#控制台輸出格式

[英]C# Console Output Formatting

我試圖例如顯示一個階乘(階乘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;
}

謝謝!

問題是您的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;語句( 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();
}

int.TryParse()將對您有所幫助,因此,如果用戶輸入非整數,則程序不會崩潰

此外,您可能還需要除整數以外的內容。 階乘非常大-超過16的任何值都會返回錯誤的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM