为什么Console.Read()没有给出我期望的整数输入值?

-8 c#

出于某种原因,VSE C#2010(或者问题出现在我的笔记本电脑中)并没有正确地解释<,>,<=和> =布尔比较运算符.

static void Main(string[] args)
    {
        Console.WriteLine("Enter an integer:");
        int myInt = Convert.ToInt32(Console.Read());
        bool isLessThan10 = myInt < 10;
        bool isBetween0and5 = (0 <= myInt) && (myInt <= 5);
        Console.WriteLine("Integer less than 10? {0}", isLessThan10);
        Console.WriteLine("Integer between 0 and 5? {0}", isBetween0and5);
        Console.WriteLine("Exactly one of the above is true? {0}",
            isLessThan10 ^ isBetween0and5);
        Console.ReadKey();
    }
Run Code Online (Sandbox Code Playgroud)
Enter an integer:
2
Integer less than 10? False
Integer between 0 and 5? False
Exactly one of the above is true? False
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 7

Console.Read读取单个字符并返回该字符的ASCII值.字符的ASCII值2不是2.

您想要读取角色并将其表示为角色,您可以通过使用Console.ReadKey(如在程序中稍后执行)或者Console.ReadLine如果您想要读取被解释为这样的字符串而不是使用来完成Console.Read.然后,您可以使用将数字的字符串表示形式转换为数字表示形式int.Parse.