-
March 4th, 2013, 04:05 PM
#1
Number Guessing
Hey,
I'm going through the book "Programming: Principles and Practice Using C++" and I am currently on chapter four. I've to make a program where the users chooses a number and the computer is to guess it. One of the rules is it is to guess in no more than seven tries.
Here is my code:
Code:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::string;
int main( )
{
int lowerBound = 1;
int median = 0;
int upperBound = 100;
string answer;
// Run through loop until the difference between bounds is 2
while ( upperBound - lowerBound >= 2 )
{
// Calculate halfway point of range
median = ( lowerBound + upperBound ) / 2;
cout << "Is your number between " << lowerBound << " and " << median << "? ";
cin >> answer;
if ( answer == "y" || answer == "Y" )
{
// Number is within range
upperBound = ( lowerBound + upperBound ) / 2;
}
else
{
// Number is not within range
lowerBound = ( lowerBound + upperBound ) / 2;
}
}
// Now there is two numbers, it is either either of them
cout << "Is your number << " << lowerBound << "? ";
cin >> answer;
if ( answer == "y" || answer == "Y" )
{
// Number is the lower bound
cout << "\n\nAnswer is: " << lowerBound << "\n\n";
}
else
{
// Number is the upper bound
cout << "\n\nAnswer is: " << upperBound << "\n\n";
}
return 0;
}
It guess with 8 or 9 tries. How could I modify it to decrease the number of tries?
Thanks,
Dash535
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|