The task is to write a game that follows the following rules:
- The computer will choose a number between given set limits and asks the player for repeated guesses until the player guesses the target number correctly. At each guess, the computer responds with whether the guess was higher than, equal to, or less than the target – or signals that the input was inappropriate.
#include <iostream> #include <cstdlib> #include <ctime> int main() { std::srand(std::time(0)); int lower, upper, guess; std::cout << "Enter lower limit: "; std::cin >> lower; std::cout << "Enter upper limit: "; std::cin >> upper; int random_number = lower + std::rand() % ((upper + 1) - lower); do { std::cout << "Guess what number I have: "; std::cin >> guess; if (guess > random_number) std::cout << "Your guess is too high\n"; else if (guess < random_number) std::cout << "Your guess is too low\n"; else std::cout << "You got it!\n"; } while (guess != random_number); return 0; }
Output:
Enter lower limit: 1 Enter upper limit: 100 Guess what number I have: 50 Your guess is too high Guess what number I have: 40 Your guess is too high Guess what number I have: 25 Your guess is too high Guess what number I have: 10 Your guess is too high Guess what number I have: 2 Your guess is too low Guess what number I have: 4 Your guess is too high Guess what number I have: 3 You got it!
Content is available under GNU Free Documentation License 1.2.