2016-09-05 2 views
0

Я написал гадать число игр между 1-100. Это мой код ..C# - Мне нужно добавить код! Угадайте номер

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

Вы действительно спрашивать: «Как я могу сказать, если число X находится в пределах 5 чисел Y»? Если это так, я предлагаю вам уменьшить свой вопрос до этого, показывая, что вы пробовали до сих пор. –

ответ

7

Вы можете использовать Math.Abs:

int diff = Math.Abs(input - randno); 
if(diff <= 5) 
{ 
    // say him that he's close 
} 
Смежные вопросы