I'm working on a question which is asking me to have a guessing game with the computer... with the computer being the guesser:
"Write a program that calculates a random number 1 through 100. The program then asks the user to guess the number. If the user guesses too high or too low then the program should output "too high" or "too low" accordingly. The program must let the user continue to guess until the user correctly guesses the number.
★ Modify the program to output how many guesses it took the user to correctly guess the right number.
★★ Modify the program so that instead of the user guessing a number the computer came up with, the computer guesses the number that the user has secretely decided. The user must tell the computer whether it guesed too high or too low."
I did the first couple bits, but I'm stuck on the two-star part, where the computer guesses the number. This is my code below, but as you'll be able to tell, it doesn't quite work as planned! I'm trying to figure out a way for the computer to remember the number it previously guessed? I tried using the if (ok == "high")
and if (ok == "low")
to create what you'd call 'boundaries' for the computer to remember. So if it was too high, it would remember the value it just guessed was too high, and would therefore guess lower than that, and vice versa with if it was too low.
But I'm struggling to get the computer to remember both parts, e.g. if my secret number was 50, the computer guessed 80. I'd say it was too high, so it would go lower. If it then guessed 40, I'd say it was too low and it would go higher. But the computer is then going HIGHER than it's original guess of 80, and sometimes even higher than 100 which I don't understand!
Any help would be appreciated :) I have no idea if I'm going the right way with this, so any pointers would help! Thank you!
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int compnumber;
string ok;
cout << "Think of a number between 1 and 100. Type 'ok' and I'll try and guess it." << endl;
cin >> ok;
cout << endl;
srand(time(NULL));
compnumber = rand() % 100 + 1;
cout << compnumber << endl;
cin >> ok;
while (ok != "correct")
{
if (ok == "high")
{
compnumber = rand() % compnumber + 1;
cout << compnumber << endl;
cin >> ok;
}
if (ok == "low")
{
compnumber = rand() % 100 + compnumber;
cout << compnumber << endl;
cin >> ok;
}
}
cout << "I won!" << endl;
}
Aucun commentaire:
Enregistrer un commentaire