/* asst03.cpp 06/09/2005 CIS 150 David Klick Solution to programming assignment #3. This program lets the user guess a number that it has chosen randomly. The user gets to choose the range (within limits) and then guess the random number within that range. The program tells the user whether their guess is correct, high, or low. */ #include #include #include using std::cin; using std::cout; int main(void) { int low, high; // low and high end of range for guessing int num; // random number to be guessed int guess; // storage for user's guess bool done; // set to true when user chooses to quit bool valid; // used to validate user input char choice; // stores whether user wants to play or quit // randomize random number generator srand(time(NULL)); cout << "This program will let you guess a number within a range\n"; done = false; while (!done) { // get low end of range valid = false; while (!valid) { cout << "Enter low end of range (0-1000): "; cin >> low; if (low>=0 && low<=1000) { valid = true; } else { cout << "Error: number not within valid range\n"; } } // get high end of range valid = false; while (!valid) { cout << "Enter high end of range (" << (low+9) << "-10000): "; cin >> high; if (high>=(low+9) && high<=10000) { valid = true; } else { cout << "Error: number not within valid range\n"; } } // choose random number num = rand() % (high-low+1) + low; cout << "Random number between " << low << " and " << high << " has been chosen\n"; // play guessing game cout << "Guess what the number is: "; do { cin >> guess; if (guess < num) { cout << "Too low. Guess again: "; } else if (guess > num) { cout << "Too high. Guess again: "; } else { cout << "You guessed it!\n"; } } while (guess != num); // find out if user wants to play again valid = false; cout << "\nPlay again? (Y/N) "; do { cin >> choice; choice = toupper(choice); if (choice=='Y' || choice=='N') { valid = true; } else { cout << "That wasn't an option. Play again? (Y/N) "; } } while (!valid); // set done to true if user wants to quit if (choice != 'Y') { done = true; } } // let user know program has ended normally cout << "Thanks for playing\n"; return 0; }