c#如何将数字输入限制为单个数字

本文关键字:单个 数字 数字输入 | 更新日期: 2023-09-27 18:01:53

对不起,这对c#新手来说可能很容易,我需要将这里的输入限制为单个数字。

 int value, value1, value2, value3, value4;
 int resultFinal, resultFirst, resultSecond, resultThird = 0;
        Console.WriteLine("Enter five single digit numbers");
        value = Convert.ToInt16(Console.ReadLine());
        value1 = Convert.ToInt16(Console.ReadLine());            
        value2 = Convert.ToInt16(Console.ReadLine());
        value3 = Convert.ToInt16(Console.ReadLine());
        value4 = Convert.ToInt16(Console.ReadLine());

        resultFirst = value - value1;
        resultSecond = value2 - value3;      
        resultThird = resultFirst + resultSecond;
        resultFinal = resultThird + value4;
        Console.WriteLine("Answer: {0}", resultFinal);
        Console.WriteLine("Press any button to close");
        Console.ReadLine();

c#如何将数字输入限制为单个数字

Console.WriteLine("Enter five single digit numbers");
List<int> list = new List<int>();
do
{
    var keyNumber = (int)Console.ReadKey(true).KeyChar;
    if (keyNumber >= 48 && keyNumber <= 57)
    {
        Console.WriteLine("Your input number is:" + (char)keyNumber);
        list.Add(keyNumber-48);
    }
    else
    {
        Console.WriteLine("Sorry, but please enter single digit numbers!");
    }
}
while (list.Count < 5);
var resultFirst = list[0] - list[1];
var resultSecond = list[2] - list[3];
var resultThird = resultFirst + resultSecond;
var resultFinal = resultThird + list[4];
Console.WriteLine("Answer: {0}", resultFinal);
Console.WriteLine("Press any button to close");
Console.ReadLine();

因为你只想让用户输入单个数字,我认为Console.ReadKey(true)更好