NumberGuesser | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

NumberGuesser

Hello, I am writing this program which will guess the number user is thinking about. After days of work, I could not figure out what is wrong in it. Please help. 1. User can guess 100, but my program uses mid-point rule so can only go up to 99. How can I make 100 inclusive? 2. If I keep pressing 'l' the program will eventually break out of loop and prints If you want to try again? 3. Any other suggestions? Here is the actual program: Write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower. The program should find the midpoint of the two numbers and ask if the number is higher or lower. TRY RUNNING MY CODE: #include <iostream> using namespace std; int main(){ char check; char tryagain; do{ int midpoint; const int MAX = 100; const int MIN = 1; int y = MAX; int x = MIN; cout<<"Think of a number between 1 and 100." << endl; midpoint = ( x + y ) / 2; while(x != y || y != x){ cout<<endl <<"Is it"<< " "<< midpoint << " "<< "?"; cin>>check; if(check=='l' || check=='L') { y = midpoint; midpoint = ( x + y ) / 2; } else if(check=='h' || check=='H') { x = midpoint; midpoint = ( x + y ) /2; } else if( check == 'c' || check == 'C') { break; } else{ cout<<"Incorrect choice."<<endl; } } cout<< "Great! Do you want to try again? (y/n)"; cout<< endl; cin >> tryagain; }while (tryagain == 'y' || tryagain != 'n'); return 0; }

21st Feb 2017, 5:36 PM
Safal Basnet
Safal Basnet - avatar
1 Answer
+ 5
//Here I have modified your code a little bit.....and now it works for 1 to 100. #include <iostream> using namespace std; int main(){ char check; char tryagain; int midpoint; constexpr int MAX = 100; constexpr int MIN = 1; do{ int y = MAX; int x = MIN; cout<<"Think of a number between 1 and 100." << endl; while(x <= y){ midpoint = ( x + y ) / 2; cout<<endl <<"Is it"<< " "<< midpoint << " "<< "?"; cin>>check; if(check=='l' || check=='L') { y = midpoint-1; midpoint = ( x + y ) / 2; } else if(check=='h' || check=='H') { x = midpoint+1; midpoint = ( x + y ) /2; } else if( check == 'c' || check == 'C') { break; } else{ cout<<"Incorrect choice."<<endl; } } cout<< "Great! Do you want to try again? (y/n)"; cout<< endl; cin >> tryagain; }while (tryagain == 'y' || tryagain != 'n'); return 0; }
14th Jun 2018, 5:30 AM
Tanay
Tanay - avatar