I had to write a program that asks the user to guess a number. The program then tells if their guess is too high or too low depending on the difference between their guess and the random number. I finished the program and it works, but my teacher's very picky about efficiency. The chapter is about controlled structures. Can someone look at this and tell me if there's a better way to write it? Mine's kinda long and doesn't seem right :\
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//declare the variables
int num; //Variable to store the random number
int guess; //Variable to store the number guessed by the user
int isGuessed; //Boolean variable to control the loop
int diff; //Variable to store the difference between the random number and guessed number
int count; //Variable to count number of tries
num = (rand() + time(0)) % 100;
isGuessed = false;
count = 0;
while (!isGuessed)
{
while (count < 5)
{
cout << "Enter an integer greater than or equal to 0 and less than 100. You have 5 guesses: ";
cin >> guess;
cout << endl;
diff = abs(num - guess); //Diff equals the difference between num and guess
if (diff == 0)
{
cout << "You guessed the correct number." << endl;
isGuessed = true;
count = 5;
}
else if (diff >= 50)
{
if (guess > num)
cout << "Your guess is very high!" << endl;
else
cout << "Your guess is very low!" << endl;
}
else if (diff >= 30)
{
if (guess > num)
cout << "Your guess is high!" << endl;
else
cout << "Your guess is low!" << endl;
}
else if (diff >= 15)
{
if (guess > num)
cout << "Your guess is moderately high!" << endl;
else
cout << "Your guess is moderately low!" << endl;
}
else
{
if (guess > num)
cout << "Your guess is somewhat high!" << endl;
else
cout << "Your guess is somewhat low!" << endl;
}
count++;
} //end while
cout << "\nGame over!" << endl;
if (isGuessed)
cout << "You win!" << endl;
else
cout << "You lose!" << endl;
isGuessed = true;
} //end while
return 0;
}
Thanks for the help! =)