I am Building guessing game C# make a âyoure closeâ answer ,closing guessing
Â
Iâm making a guessing game (guess between 1-1000). and I need answer that Iâm wrong but was close. I have the code (int diff = Math.Abs(guess - num); if (diff <= 3)
 but I donât know where to putt it.
I have made to that I have a number that is right so that it is easier to to see if I have done my code right (and will change it after)
Console.WriteLine("gissa talet\nDu ska nu gissa ett tal mellan 1 ocn 100, sÄ
varsÄgod..\nskriv in ett tal");
int guess = Convert.ToInt32(str);
//gonna make it random between 1-100
int num = (50);
{
//when im right
if (guess == num)
{
Console.WriteLine("rÀtt");
}
//when itÂŽs to small guess
else if (guess < num)
Console.WriteLine("för lite");
// to large guess
if (guess > num)
Console.WriteLine("för stort");
// when i make it random nr and i guess over 100
if (guess > 50)
Console.WriteLine("gissa mellan 1-100");
Console.ReadLine();
}
To add the âyouâre closeâ answer to your guessing game, you can use the Math.Abs()
function to calculate the difference between the userâs guess and the correct number. If the difference is less than or equal to 3, you can display the âyouâre closeâ message.
Hereâs the updated code with the âyouâre closeâ answer:
Â
using System;
namespace GuessingGame
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int num = random.Next(1, 101); // Generate a random number between 1 and 100
Console.WriteLine(âGuess the number!\nYou should now guess a number between 1 and 100, so go ahead..\nEnter a number:â);
int guess = Convert.ToInt32(Console.ReadLine());int diff = Math.Abs(guess â num);
if (guess == num)
{
Console.WriteLine(âCorrect! You guessed the right number.â);
}
else if (guess < num)
{
Console.WriteLine(âToo small.â);
}
else if (guess > num)
{
Console.WriteLine(âToo large.â);
}if (diff <= 3)
{
Console.WriteLine(âYouâre close!â);
}Console.ReadLine();
}
}
}
With this code, if the userâs guess is within 3 numbers of the correct number, the âYouâre close!â message will be displayed along with the appropriate âToo smallâ or âToo largeâ message. If the guess is exactly correct, the âCorrect! You guessed the right number.â message will be displayed.