我写了一个猜测1-100之间的数字游戏。 这是我的代码..
class Program
{
static void Main(string[] args)
{
while (true)
{
int randno = Newnum(1, 101);
int count = 1;
while (true)
{
Console.Write("Guess a number between 1 and 100, or press 0 to quit: ");
int input = Convert.ToInt32(Console.ReadLine());
if (input == 0)
return;
else if (input < randno)
{
Console.WriteLine("Unlucky, that number is too low - have another go!");
++count;
continue;
}
else if (input > randno)
{
Console.WriteLine("Unlucky, that number is too high - have another go!");
++count;
continue;
}
else
{
Console.WriteLine("Well done - you guessed it! The number was {0}.", randno);
Console.WriteLine("It took you {0} {1}.\n", count, count == 1 ? "attempt" : "attempts to guess it right");
break;
}
}
}
}
static int Newnum(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
如何编辑它,以便如果用户接近该号码,比如在5个数字内,他们会收到一条消息说他们已经关闭了?
答案 0 :(得分:7)
您可以使用Math.Abs
:
int diff = Math.Abs(input - randno);
if(diff <= 5)
{
// say him that he's close
}