So i finally solved the bracketing search beginner excercise!
And, to learn c++ better, i usually come here to ask for more
efficient ways of writing the program, after i have made an attempt myself.
#include<iostream>
#include<cmath>
#include<string>
usingnamespace std;
int main() {
int maximum = 100;
int minimum = 0;
int guess;
int secretnumber;
int count = 1;
string i;
cout << "Enter a number between 1 and 100, that the computer will guess." << endl;
cin >> secretnumber;
do {
guess = (( maximum + minimum ) / 2 );
if ( guess == secretnumber )
break;
cout << "Is the secret number higher or lower than " << guess << "?" << endl;
count ++;
cin >> i;
if ( i == "higher" )
minimum = ( guess + 1 );
elseif ( i == "lower" )
maximum = (guess - 1);
else { cout << "That's not a valid answer. Try again." << endl;
break; }
}
while ( guess != secretnumber);
cout << "The number is " << guess << " and i solved it in " << count << " guesses!" << endl;
system("pause");
return 0;
}
Any ways those who are more experienced would have solved this?
I'd love to know. Thanks.
#include <iostream>
int main(void) {
int num, compGuess;
int max = 100, min = 0, count = 1;
std::cout << "Enter a number between 0 and 100: ";
std::cin >> num;
while(compGuess != num && count < 8) {
compGuess = (max + min) / 2;
std::cout << compGuess << " is <h>igher, <l>ower or <c>orrect? ";
char ch;
std::cin >> ch;
(ch == 'h'?max:min) = compGuess;
++count;
}
std::cout << "The nunber is " << num << " and it was solved in " << count-1 << " guesses!\n";
return 0;
}
My only complaint is the system call towards the end of main.
Could you elaborate xhtmlx?
Obviously im new to this... :)
Also, i disagree on using chars and <l>ower etc. when strings are more user friendly, and sometimes easier to work with. Though you are correct, it is more efficient, which was what i originally asked for.
if you want comp to guess 100, max should be 101, because of integer division.
suppose you set min = 0, max = 100
number: 100
50 (100/2) ? higher
75 (150/2) ? higher
87 (175/2) ? higher
93 (187/2) ? higher
96 (193/2) ? higher
98 (196/2) ? higher
99 (198/2) ? higher
99 (199/2) ? higher
99 (199/2) ? higher
99 (199/2) ? higher
...
and on and on and on... even if you set limit count < 8 the computer will not be able to guess the correct answer 100.