簡體   English   中英

C# 如何將非數字值設置為 0

[英]C# How set a non-numeric value to 0

我必須編寫一個代碼來要求 3 個整數值並找到最大的一個。 但是,如果用戶輸入一個非數字值,則該值必須為零。 到目前為止我寫了這個

        int a, b, c;

        Console.WriteLine("Enter value 1:");
        a = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter value 2:");
        b = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter value 3:");
        c = Convert.ToInt32(Console.ReadLine());

        if (a > b && a > c)
        {
            Console.WriteLine("The greatest value is: {0}", a);
        }
        if (b > a && b > c)
        {
            Console.WriteLine("The greatest value is: {0}", b);
        }
        if (c > a && c > b)
        {
            Console.WriteLine("The greatest value is: {0}", c);
        }

此代碼僅適用於數字。 我的問題是我不能讓非數字輸入的值為零。 我嘗試使用字符串而不是 int,所以沒有錯誤,但我不能在 if 語句中使用 ">" 字符串,我也嘗試使用默認值,因為默認值是什么,所以它為零。

謝謝

你可以替換:

x = Convert.ToInt32(Console.ReadLine());

和...

int.TryParse(Console.ReadLine(), out int x);

如果無法解析輸入,則x最終將為 0。

我認為您可以創建一個執行 try catch 的 function,這樣您就可以打印一條消息,說明輸入不是數字。

static int Check(string input)
        {
            int result;
            try
            {
                result = Convert.ToInt32(input);
            }
            catch (FormatException e)
            {
                Console.WriteLine("Input not integer, the value assigned is 0");
                result = 0;
            }
            return result;
        }

為了實現你只需調用:

a = Check(Console.ReadLine());

暫無
暫無

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

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