Guessing game random number to static

2019-09-11 09:20发布

问题:

I have created a guessing game that generates a random number, takes the user's guess, and basically outputs whether the user's guess is too high or too low(outputs blue, colder) or closer (warmer, outputs red) using both a text box background color and label, as you can see in my code. The issue I am having difficulties with is that every time I click submit, the program generates a new random number. I would like for the program to use the same number until the user's guess is correct, then it can generate a new number if the user would like to play again.
I'm thinking about using a while loop, such as

How could I possible make the random number stay static (same) until it's guessed correctly and if I do need a while loop, where would be the ideal place to place it?

回答1:

Assign the generated random number to a variable, and then use that variable until you need a new random number.

In this particular instance, the line of code number = rand() % 1000 + 1; needs to be outside of your button click method. Otherwise, every time you click the button, it will generate a new random number.



回答2:

What you want to do is move your number variable's declaration to the top of the class, outside any functions, like so:

class NumberGuessingGame
{
    public: int number = 0;
}

Then, in your MyForm_Load method, you can generate the random number, and set it's value to that variable, like:

private: System::Void MyForm_Load()
{
    //Set the value of number here to a newly generated random integer
}

You should then be able to access the number variable inside your button1_Click function:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
    if (input > this->number)
    {
        //code
    }

    //Rest of your ifs
}