Guess the number

MrDevo

New member
Joined
Apr 10, 2014
Messages
1
Programming Experience
Beginner
Hi. I am pretty new to C# and trying to get this game to work. I got a textbox where I type the number that I have in mind and the computer must guess it using bisection algorithm but I don't understand why the loop won't work since the condition is true. Here's my code. The biggeest and the minimum have their values set to "0" and "100".

private void btnGuess_Click(object sender, EventArgs e)
{
    bool guess = true;
    Convert.ToInt32(txtNumber.Text);
    nrToGuess = int.Parse(txtNumber.Text);
    DialogResult dialogResult;

    do
    {
        average = minimum + biggest / 2;
        dialogResult= MessageBox.Show("Is your number" + " " + average+ " ? ", "Question", MessageBoxButtons.YesNo);

        if (dialogResult== DialogResult.No && average > nrToGuess)
        {
            biggest = average;
            average = biggest + minimum / 2;
        }
        else if (dialogResult == DialogResult.No && average < nrToGuess)
        {
            minimum = average;
            average = biggest + minimum / 2;
        }
        else if (dialogResult == DialogResult.Yes)
        {
            dialogResult=MessageBox.Show("Congratulations! You guessed the number!");
            break;
        }
        else
       {
           Application.Exit();
       }
    } while (guess);

I would really appreciate any help given. Thank you very much!
 
Last edited by a moderator:
First things first, when posting code snippets, please paste them as plain text inside formatting tags. I have fixed your post and, as you can see, the code is much easier to read. Indenting in particular is critical to make code readable.

Secondly, please don't just say that something doesn't work. We don't know what's in your head. Explain what you expect to see and what you actually see.

With that second point in mind, have you debugged the code? If code doesn't work the way you expect, don't just read it; watch it in action. Place a breakpoint at the top of the code (F9) and then step through it line by line (F10). You can use tools like the Autos, Locals, Watch and Immediate windows to evaluate the state of the application at each step and you can therefore compare reality to expectation. As soon as they differ, you have found the location of an issue and you can determine what variables, etc, do not hold the values you expect or, if they all do, where your logic is faulty. If you still can't fix the issue, at least you can give us a detailed explanation of where the error occurs and the state of the app when it happens. That way we can concentrate on fixing the problem rather than working out where it might be.
 

Latest posts

Back
Top Bottom