I'm creating a little number guessing game for class and I have a question that my prof still hasn't spoken about:
In my if-statements I have different messages telling the player when the guess is < random number, > the random number and == the random number. Now I would like to also print a message when the guess is too far off the random number;
If the random number is 700 and my guess is more than 100 off, how do I put this in the if-statement? I have of course tried guess >100 but that obviously doesn't work. Do I need a new variable for this?
CodePudding user response:
Either your guess will be 100 bigger or smaller then your number.
int randomNr = 350;
int guess = 250;
int maxOff = 100;
if (guess - randomNr > maxOff || randomNr - guess > maxOff)
{
//Show message.
}
CodePudding user response:
You can do something like this.
if (Math.Abs(guessedNumber - randomNumber)> 100){
Console.WriteLine("Your number is so far from the random number")
}
CodePudding user response:
Always try to include your code when asking a question.
Without having your code, this is a potential solution to your question :
1. Print message telling by how much the guess is off
int diff;
diff = random - guess;
if(diff > 0)
{
Console.WriteLine($"guess is smaller by {diff}");
}
else if(diff < 0)
{
Console.WriteLine($"Guess is greater by {diff}");
}
CodePudding user response:
You can try this
public static int rand = new Random().Next(0, 999);
public static string myNumber;
static void Main(string[] args)
{
Console.WriteLine("Guess the random number");
do
{
myNumber = Console.ReadLine();
IHopeIguessRandomNumber(Convert.ToInt32(myNumber));
}
while (Convert.ToInt32(myNumber) != rand);
}
public static void IHopeIguessRandomNumber(int myGuess)
{
if ( myGuess == rand)
{
Console.WriteLine("You're right! This is the right number");
}
else if (myGuess <= rand - 100)
{
Console.WriteLine("Too Low! Your number is < random");
}
else if ( myGuess < rand)
{
Console.WriteLine("Your number is < random");
}
else if (myGuess >= rand 100)
{
Console.WriteLine("Too Big! Your number is > random");
}
else if (myGuess > rand)
{
Console.WriteLine("Your number is > random");
}
}
Have a nice day :)
CodePudding user response:
You can use a NESTED IF block like this.
if(guessNum < randomNum)
{
if(guessNum < randomNum - 100)
{
Console.WriteLine("The guessed number is too Low");
}
else
{
Console.WriteLine("The guessed number is Low, but you are close");
}
}
else if(guessNum > randomNum)
{
if(guessNum > randomNum 100)
{
Console.WriteLine("The guessed number is too High");
}
else
{
Console.WriteLine("The guessed number is High, but you are close");
}
}
I can help you with the exact answer if you add the existing code snippet.