# Using random numbers

We are learning to use the
srand(time(NULL))
rand()%11
function command things, and our teacher asked us to make a "game" so to speak where the user enters a number, then the computer trys to guess it, you have to use while loops also. I tried this. (number being the users entered number, compguess being the random number the computer picks)
int compguess = rand()%number;
while(compguess != number)
{
count = count + 1; //to keep the amount of guesses
cout<<compguess<<" was wrong"<<endl;
}
cout<<"The computer took "<<count<<" times"<<endl;
well that just gave me a big long scrolling list of one number being wrong, can someone please tell me how I could go about doing this a.s.a.p. sorry its so long.
###### Who is Participating?

Commented:
You need to set compguess every time you iterate through the loop.
while(compguess != number)
{
count = count + 1; //to keep the amount of guesses
cout<<compguess<<" was wrong"<<endl;
compguess = rand()%number;
}

0

Commented:
In a case like this it as always a good idea to STEP through your code and see what the code you wrote really does.

Take a pen and paper and write down the variables after each step (or only the ones that changed). If you did this you would see why you got the same value all the time and it would be easy to spot the problem.

After doing this a number of times on paper it gets easier to step through with the values in your head to check your code.
0

Commented:
>while(compguess != number)
>     {
>      count = count + 1; //to keep the amount of guesses
>      cout<<compguess<<" was wrong"<<endl;
>      compguess = rand()%number;
>     }

does this produce an infinite loop?  i mean, won't rand()%number result in a number between 0 and (number - 1) inclusive?
sorry about the daft question, but perhaps i don't understand the % operator.

0

Commented:
mmachie.

Quite right, the original question seemed to expect a number in the range 0-10 (inclusive) so this should be:-

compguess = rand() % 11;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.