Help with my guessing programm

Hey guys, I tried to create a program which guesses the number of the user and by asking if the guessed number is below or above the users number the computer will create a new guess. Works perfect only has a problem, which is that the programm cant guess max=100. I tried to do it with double, but this also takes 21 guesses, which is quite high. Is there any other way i can better my function?

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
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

int choice, x, nmbr;
int guess (int&, int&);
int main(){
int max =100;
int min=1;

cout << "The computer will guess your number" << endl;
do{
nmbr = guess(min, max);
x++;
cout << "Is your Number: " << nmbr << "?" << endl;
cout << "Its your number=0, too  low=1, too high=2" << endl;
cin >> choice;
if(cin.fail()){
cout << "Invalid input!" << endl;
return 1;
}
if(choice ==1){
cout << "Number is too low - generating new number under " << nmbr << endl;
min = nmbr;

}else if(choice == 2){
cout << "Number is too high - generating new number above " << nmbr << endl;
max = nmbr;

}
}while(choice != 0);
cout << "Right number was guessed!\nTries: " << x << "\nExecuting Programm" << endl;

return 0;
}//end main()

int guess(int& var1, int& var2){
return ((var2-var1)/2)+var1;
}


thank for any help
Assuming that you are only allowing the values from 1 - 100 any number can be guessed correctly within 7 guesses. This is possible by simply eliminating half of the remaining numbers with each guess. For example the user enters the number 24

Guess 1 = 50; --> too high
Guess 2 = 25; --> too high
Guess 3 = 13; --> too low
Guess 4 = 19; --> too low
Guess 5 = 22; --> too low
Guess 6 = 23; --> too loe
Guess 7 = 24; --> Correct

Another example the user enters the number 76
Guess 1 = 50; --> too low
Guess 2 = 75; --> too low
Guess 3 = 86; --> too high
Guess 4 = 80; --> too high
Guess 5 = 77; --> too high
Guess 6 = 76; --> correct

If you adjust your logic to this, you will be guaranteed to guess the number in 7 or less. The same logic could be used for more, but the number of guesses required may change.
I cant really understand your answer, but I think I fixed it with an if-statement in the function
1
2
3
4
5
6
7
int guess(int& var1, int& var2){
if(var1 == 99){ // min=99
    var2=100;
    return var2;
}
return ((var2-var1)/2)+var1;
}
I find this works...

1
2
3
4
5
6
7
int guess(int& var1, int& var2) {
	float result = ((var2 - var1) / 2.0) + var1;
	if (result > 99) {
		result = 100;
	};
	return result;
}
Topic archived. No new replies allowed.