Start learning today, and be successful in your academic & professional career. Start Today!

Loading video...

This is a quick preview of the lesson. For full access, please Log In or Sign up.

For more information, please see full course syllabus of Introduction to C++

For more information, please see full course syllabus of Introduction to C++

0 answers

Post by Donald Sullenger on October 7, 2015

I'm having a heck of a time with homework number 6 (the computer guessing problem). I'm sure I'm missing something simple but I'm just not coming up with it. My code works through the second guess (whether high or low) but, after that, it just repeatedly picks the same number (eg., 100/2 = 50; 50/2 = 25; then it keeps picking 25. This is because the variables have a set formula but I don't see how to get the computer to take the result of the second guess and apply the formula to that result. Where am I going wrong here?

#include "stdafx.h"

#include <iostream>

using namespace std;

int main()

{

int max = 100;

int min = 1;

int firstGuess = max / 2;

int highGuess = ((firstGuess + 1) / 2);

int lowGuess = ((max + 50) / 2);

char correct = 'y' || 'n';

int counter = 1;

cout << "I know your number is between 1 and 100. I'll guess it!

" ;

cout << "Is your number " << firstGuess << "? (Enter 'y' or 'n') " ;

cin >> correct;

// if first guess was correct, display message and end program

if (correct == 'y') {

cout << "I told you I was good!

" ; }

// if first guess was wrong, begin binary search for correct number

else {

do {

cout << "Was I too high or too low? (Enter 'h' or 'l') " ;

char answer = 'h' || 'l';

cin >> answer;

// if firstGuess was too high, take product of firstGuess and

// divide in half.

if (answer == 'h') {

cout << "Is your number " << highGuess << "? " ;

cin >> correct; }

// if firstGuess was too low, add range maximum and midpoint

// then divide by two

else if (answer == 'l') {

cout << "Is your number " << lowGuess << "? " ;

cin >> correct; }

} while (correct == 'n') ;

while (correct == 'n') {

cout << "That is " << counter << " incorrect answer so far.

" ;

counter++; }

}

return 0;

}

1 answer

Last reply by: Alvin Sylvain

Sun May 5, 2013 7:23 PM

Post by yufeng wang on May 2, 2013

at 7:31, why do we have to define int guess =0?

i thought it's enough to define guess, but not to give it a value 0?