为什么此C#代码输出错误的整数?

时间:2018-09-04 17:29:46

标签: c#

因此,我目前正在尝试完全没有经验的C#编程。因此,我尝试制作一个简单的程序来读取用户输入并将其再次输出给用户。现在,名字部分就很好了,但是当我尝试输入我的年龄作为前者时。 20岁,它总是写“您的输入已保存。您49岁。”无论我输入什么数字,它总能给我49,并且我看不到任何会导致此问题的代码问题。你知道怎么了吗?

        Console.Write("Insert Age: ");
        int age = Convert.ToInt32(Console.Read());
        if (age < 18)
        {
            Console.WriteLine("Whoops! Looks like you are only " + age + " Year(s) old! You are too young to have your input saved.");
        }
        else
        {
            Console.WriteLine("Your input has been saved. You are " + age + " Year(s) old.");
        }

3 个答案:

答案 0 :(得分:1)

Console.Read()方法仅从控制台读取一个字符。如果要读取数字(例如20或77),则需要 Console.ReadLine()方法。这将读取包含您的电话号码的整行。

我强烈建议您使用 int.TryParse()方法而不是 Convert.ToInt32()方法,因为在某些情况下,转换将失败。例如,如果某人以错误的格式键入输入内容,他将引入以下行: 20a 。然后您的程序将崩溃。

使用 int.TryParse()方法非常简单。您的代码将如下所示:

    Console.Write("Insert Age: ");
    if( true == int.TryParse(Console.ReadLine()) )
    {
       if (age < 18)
       {
          Console.WriteLine("Whoops! Looks like you are only " + age  
                          + " Year(s) old! You are too young to have your input saved.");
       }
       else
       {
          Console.WriteLine("Your input has been saved. You are " 
                             + age + " Year(s) old.");
       }
    }
    else
    {
       Console.WriteLine("This is not a number."); // Or any message you want
    }

要使这段代码更短,您可以尝试编写如下代码:

    Console.Write("Insert Age: ");
    if( true == int.TryParse(Console.ReadLine()) )
    {
       Console.WriteLine( age < 18 ? 
         "Whoops! Looks like you are only " + age + 
         " Year(s) old! You are too young to have your input saved." :
         "Your input has been saved. You are " + age + " Year(s) old.");
    }
    else
    {
       Console.WriteLine("This is not a number."); // Or any message you want
    }

如果您想更短些,请尝试:

    Console.Write("Insert Age: ");
    Console.WriteLine( int.TryParse(Console.ReadLine()) ?
       (age < 18 ?
            "Whoops! Looks like you are only " + age 
             + " Year(s) old! You are too young to have your input saved." 
         : "Your input has been saved. You are " + age + " Year(s) old.") 
      : "This is not a number.");

答案 1 :(得分:0)

Console.Read()仅从标准输入中读取下一个字符, Console.ReadLine()会从标准输入流中读取下一行字符。


来自@VMAtm

来源逐字记录: Difference between Console.Read() and Console.ReadLine()?

答案 2 :(得分:0)

该问题是基本的理解问题。 .NET在这里可以完成所有工作。

请查看Console.Read()方法。如您所见,它返回一个Int32值。在您的情况下,这意味着:它读取输入流的第一个char。如果在控制台中输入“ 23”,则2被认为是char,根据ASCII,它表示值 50 。之后,您将这个 50 转换为整数:age = 50

可能的解决方案

根据MSDN

int age = Convert.ToInt32(Console.ReadLine());

希望有帮助。