LOOPS
Let diff = the absolute value of (num – guess). If diff is 0, then guess is correct. diff is not 0. Then the program outputs the message as follows:
1. If diff is greater than or equal to 50, the program outputs the message indicating that the guess is very high (if guess is greater than num) or very low (if guess is less than num).
2. If diff is greater than or equal to 30 and less than 50, the program outputs the message indicating that the guess is high (if guess is greater than num) or low (if guess is less than num).
3. If diff is greater than or equal to 15 and less than 30, the program outputs the message indicating that the guess is moderately high (if guess is greater than num) or moderately low (if guess is less than num).
4. If diff is greater than 0 and less than 15, the program outputs the message indicating that the guess is somewhat high (if guess is greater than num) or somewhat low (if guess is less than num).
Give the user no more than five tries to guess the number.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int num = rand() % 100;
cout << "I thought of a number. Can you guess it?" << endl;
int guess;
for (int i=0; i<5; i++) {
cout << "Your guess: ";
cin >> guess;
int diff = abs(num - guess);
if (diff == 0) {
break;
}
if (diff >= 50) {
cout << "The guess is very ";
}
else if (diff >= 30) {
cout << "The guess is ";
}
else if (diff >= 15) {
cout << "The guess is moderately ";
}
else {
cout << "The guess is somewhat ";
}
if (guess > num) {
cout << "high." << endl;
}
else {
cout << "low." << endl;
}
}
if (guess == num) {
cout << endl << "Yes! The guess is correct!" << endl;
}
else {
cout << endl << "Sorry, you are out of trays. "
<< "I thought of " << num << endl;
}
}
Comments
Leave a comment