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.