【问题标题】:Relational Operator Statement And Output Don't Seem To Match关系运算符语句和输出似乎不匹配
【发布时间】:2020-04-20 06:25:10
【问题描述】:

大家好,我是 C# 新手,目前正处于试验 if-else 语句的阶段。在声明变量 ageUserpermittedAgeinput 并运行程序后,我注意到 if 语句和结果输出似乎不匹配.

        int ageUser;
        int permittedAge = 18;
        int input;

        Console.Write("Put in your age: ");
        input = Convert.ToInt32(Console.Read());
        ageUser = input;

        if (ageUser < permittedAge)
        {
            Console.WriteLine("Sorry you are not permitted to enter this site!");
        }

        else
        {
            Console.WriteLine("Welcome");
        }

Link To Console Output

【问题讨论】:

  • Convert.ToInt32(Console.Read()); 应该是 int.Parse(Console.ReadLine());。你在调试ageUser的值时应该已经发现了错误的结果
  • 你好,丹尼。我认为您必须使用 Console.ReadLine 而不是 Console.Read。 Console.Read 只读一个字符。
  • 感谢@Jean-ClaudeColette 的澄清。
  • @UnholySheep 如果我可以问,什么时候使用Convert.ToInt32(Console.Read());int.Parse(Console.ReadLine()); 比较合适?
  • 我想不出Convert.ToInt32(Console.Read()); 是正确使用的任何情况,但可能有一些用例。在大多数情况下,您希望使用Console.ReadLine() 读取用户输入(而int.ParseConvert.ToInt32 是不同的讨论:stackoverflow.com/questions/199470/…

标签: c# relational-operators


【解决方案1】:

您需要更改在输入中的阅读方式。 Read() 读取一个字符,并且不会像您认为的那样将其转换为 int 。 (由于其 ASCII 表示,5 变为 53)。请改用ReadLine

请改用以下内容。

    Console.Write("Put in your age: ");
    input = Convert.ToInt32(Console.ReadLine());
    ageUser = input;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2013-09-29
    • 1970-01-01
    相关资源
    最近更新 更多