Firmino11 Firmino11 - 2 months ago 19
C# Question

C# - I need to add code! Guess the number

I have written a guess the number game between 1-100.
This is my code..

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);
}
}


How can I edit it so that if a user gets close to the number, say within 5 numbers, they are greeted with a message saying they're close?

Answer

You can use Math.Abs:

int diff = Math.Abs(input - randno);
if(diff <= 5)
{
    // say him that he's close
}
Comments