C# 程序不评估操作并返回错误答案

标签 c# windows oop cmd notepad++

社区。

我正在学习如何使用 C# 编程。我编写了这个小程序,它从用户那里获取姓名、年龄、最喜欢的颜色和两个数字。我使用 Notepad++ 编写代码并从 Windows 命令提示符运行 C# 编译器。这是程序的源代码

using System;

class ShowSomething
{
static void Main(string[] args)

{
    string name, age, favColor;
    int num1,num2, sum, mult, subs;
    float div;


    Console.Write("What is your name? ");
    name = Console.ReadLine();
    Console.WriteLine("Hello, " + name);

    Console.WriteLine();

    Console.Write("How old are you? ");
    age = Console.ReadLine();
    Console.WriteLine("So you are " + age, "I thought that you were older!");

    Console.WriteLine();

    Console.Write("What is your favorite Color? ");
    favColor = Console.ReadLine();
    Console.WriteLine(favColor + " is a cool color!");

    Console.WriteLine();

    Console.WriteLine("Nice meeting you, " + name, "Have a good day!");

    Console.WriteLine();

    Console.WriteLine("Let us do some operations, " + name);

    Console.WriteLine();

    Console.Write("Please enter a number: ");
    num1 = Console.Read();

    Console.Write("Please enter another number: ");
    num2 = Console.Read();

    sum = num1 + num2;
    mult = num1 * num2;
    subs = num1 - num2;
    div = num1 / num2;


    Console.WriteLine();

    Console.WriteLine("Alright, " + name, "Let us blow up your mind!");

    Console.WriteLine();

    Console.WriteLine(num1 + "+" + num2, "=" + sum);
    Console.WriteLine(num1 + "*" + num2, "=" + mult);
    Console.WriteLine(num1 + "-" + num2, "=" + subs);
    Console.WriteLine(num1 + "/" + num2, "=" + div);

    Console.WriteLine();
    Console.WriteLine("Mindblown, Right?");
}   

}

当我执行程序时,几乎一切正常。但是,当用户输入第一个操作数时,程序会跳过第二个提示并打印出与预期完全不同的结果。例如,如果我将 0 作为第一个数字,程序将跳转到操作并打印以下内容:

//

48+13

48*13

48-13

48/13

脑残,对吧?

//

最佳答案

不要使用 Console.Read因为它没有做预期的事情:

Reads the next character from the standard input stream (and returns the integer value1 that represents it).

这里有一个来自 devshort 的关于为什么第二次调用 Console.Read “跳过”的很好的解释:

If you enter in the value "1" for the first thing, it'll convert that to the ascii representation. Then the carriage return is STILL in the screen [input] buffer, so when you hit the next read (Console.Read) it reads the newline and converts it to a number.

相反,一种方法是使用 Console.ReadLine相反(返回一个字符串)与 int.Parse 结合使用或类似的..


1 提示:carriage return字符的值为 13。

关于C# 程序不评估操作并返回错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864726/

相关文章:

python - python中不同参数类型的方法重载

c# - 单击时如何使内容切换向下/向上滑动

c# - 检查 XML 中空子节点的最佳方法?

c++ - 适用于 Linux(和 Windows)的异步 C++ 通信库

arrays - Kotlin 中的多维对象数组

java - 让每个具体类都从接口(interface)继承是错误的吗?

c# - 更改WPF中的鼠标拖动光标

c# - 使用 DefaultCascade.All() 将实体添加到列表时,Nhibernate 不会设置 Id

windows - 检查 Windows 批处理文件中是否对当前网络连接进行计量

c - Linux 中 WaitForSingleObject() 和 ResetEvent() 的等效性