我是编程c#的新手。我试图编写一个在cmd中运行的简单程序。我认为它会随机创建一个noumber,用户会输入数字,他/她会尝试猜测随机创建的数字。程序会告诉你它是否低于或高于你输入的数字......我开始编程但是我遇到了问题...我无法比较用户输入的noumber和随机生成的数字。
这是代码......
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the number!");
Random randomObject = new Random();
int RandNoumber = randomObject.Next(9999) + 1;
ConsoleKeyInfo keyinfo = Console.ReadKey();
if (keyinfo < RandNoumber) //This is where I got an error msg
{
}
}
}
感谢您的支持!
MP
答案 0 :(得分:1)
您可以使用Consol.ReadLine
然后解析用户输入的值
static void Main(string[] args)
{
Console.WriteLine("Guess the number!");
Random randomObject = new Random();
int RandNoumber = randomObject.Next(9999) + 1;
int enteredNumber;
while (true)
{
bool parsed = int.TryParse(Console.ReadLine(), out enteredNumber);
if (parsed)
{
if (enteredNumber < RandNoumber)
{
Console.WriteLine("Wrong it's higher");
}
else if (enteredNumber > RandNoumber)
{
Console.WriteLine("Wrong it's lower");
}
else
{
Console.WriteLine("Good Job!");
//Do victory dance
return;
}
}
else
{
Console.WriteLine("Please enter a number");
}
}
}