Guess My number game question.

So I wrote a program for a guess my number game in which I try to guess a number that the computer chooses from 1-100. Now my question is how do I change the code in which me and the computer switch places. So the computer trys to guess a number that I choose.
Here's the code.

// Guess My Number

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
srand(time(0)); // seed random number generator

int TheNumber = rand() % 100 + 1; // Random number between 1 and 100
int tries = 0, guess;

cout << "\tWelcome to Guess My Number\n\n" << endl;

do
{
cout << "Enter a guess: " << endl;
cin >> guess;
++tries;

if (guess > TheNumber)
cout << "Too High!!\n\n" << endl;
if (guess < TheNumber)
cout << "Too Low!!\n\n" << endl;
} while (guess != TheNumber);
cout << "\nThat's it! you goit it in " << tries << " guesses!\n" << endl;

int exit;
cin >> exit;

return 0;

}
All you need to do is to generate random numbers in a given range.
Good question. Well first is the obvious bit.

You have to get the computer to ask if the number is right and you have to enter if its is too high or too low.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

int main(){

cout<<"Think of a number!"<<endl;
bool keepGoing=true;
int guess =0;

  while(keepGoing){

          char answer;
          cout<<"Is your number: "<< guess<<endl << "Y/N"<<endl;
          cin << answer;

          if (char == 'Y') keepGoing=false;

           else {
                   char higherAnswer
                   cout<<"Is your number higher?"<<endl<<"Y/N"<<endl;
                   cin << higherAnswer;
                   guess=5; // always guesses 5
                   }
  }

cout<<"Yay, I got the answer!"<<endl;
return 0;
}


*Disclaimer: Code has not been proofread, do not assume is correct*


Now, if you actually read the program, you will see that it always guesses that the answer is 5. The interesting part is how to get the computer to guess something. There's a number of methods that can be used to do this, the simplest methods being to guess a random number, or to just go through all the numbers in order.

Hope you have fun with this program.
Topic archived. No new replies allowed.