Question: I am getting an error in my code where the variable guess is being used without being initialized. This is for a number guessing game

I am getting an error in my code where the variable guess is being used without being initialized. This is for a number guessing game in c++ and at the end the game asks if you want to play again. what doesn't work is if I select H for guess higher or L for lower. Can someone help me fix my code?

source code:

#include

using namespace std;

int main() { int high = 100, low = 1, midpoint; midpoint = (high - low) / 2; int guess, // the guess the program outputs mid; //the new midpoint between the remaining values.

char ch = 'y';

do { cout << "Think of a number between 1 and 100. "; cout << "Is it " << midpoint << "? (h/l/c): "; cin >> ch;

if (ch == 'c') { cout << "Great! Do you want to play again? (y/n): "; cin >> ch;

if (ch == 'y') cout << "Is it " << midpoint << "? (h/l/c): "; }

switch (ch) { case 'h': if (midpoint > guess) mid = (midpoint - guess) / 2; else mid = (guess - midpoint) / 2;

if (mid == 0) mid++; guess = midpoint; midpoint = guess + mid; break;

case 'l': if (midpoint > guess) mid = (midpoint - guess) / 2; else mid = (guess - midpoint) / 2;

if (mid == 0) mid--; guess = midpoint; midpoint = guess - mid; break;

default: cout << "invalid input"; }

}while (ch == 'y');

return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!