简体   繁体   中英

How to make my program say that I'm close or far from the answer and then to input it again? C#

Here I have the program that selects random number for me to guess. How can I make it now to say that number is close or far away from original random selected by the program?

using System;


namespace higherlower_guesser
{
class Program
{
    static void Main(string[] args)
    {


        Random rnd = new Random();
        int randomNumber = rnd.Next(0, 100);


        bool answerCheck = false;
        int guessAttempts = 0;

        
        while (answerCheck == false)
        {
            Console.Clear();
            Console.WriteLine("Take a guess.");
            guessAttempts++;
            int enteredValue = int.Parse(Console.ReadLine());
            if (enteredValue == randomNumber) 
            {
                Console.WriteLine("Congratulations, the number in mind is {0}. You've had {1} attempts", randomNumber, guessAttempts);
                answerCheck = true;
            }
          }
        }
      }
    }

You need to define what "close" and "far" are for your app. You can do something like:

const int CloseRange = 10;

if (enteredValue <= CloseRange) { /* we are close! */ }
else { /* we are far! */ }

You can check the distance of the input guess to answer in the "While" loop.

while (answerCheck == false)
    {
        Console.Clear();
        Console.WriteLine("Take a guess.");
        guessAttempts++;
        int enteredValue = int.Parse(Console.ReadLine());
        if (enteredValue == randomNumber) 
        {
            Console.WriteLine("Congratulations, the number in mind is {0}. You've had {1} attempts", randomNumber, guessAttempts);
            answerCheck = true;
        }
        else if(Math.abs(enteredValue - randomNumber) < 10)
        {
            Console.WriteLine("Your guess is close to answering! Try again."); 
        }
        else
        {
            Console.WriteLine("Your guess is so far! Try more.");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM