社区。
我正在学习如何使用 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/