我用C#编写了一个基本的猜数字游戏。似乎无论用户选择什么var c,每次都会返回第三个选项(“选择错误!请重试。”)。我正在尝试使用字符(用c作为字符串,用s代替1,用w代替2等等),但是它给出了相同的结果。不知道哪里会变坏。
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}
答案 0 :(得分:3)
如之前的注释中所述,Console.Read()
返回一个字符代码。数字1的字符代码为49,因此您的条件失败并且执行else块。
您想要做的是使用Console.ReadLine()
返回一个字符串而不是字符代码。如果将string
转换为Int32
,则应该能够正确评估条件。