srand( 0 );
int points; // number of points
float computerNumber; // number generated by the computer
float guess; // user's guess
char quit; // What the user enters when they want to quit
int totalPoints; //the total score of all of the games played
int avgPoints; // the average score of all games played
int gamesPlayed; // how many games have been played
float rangeLow; // the lower end of the range
float rangeHigh; // the higher end of the range
points = 5;
quit = 'n';
gamesPlayed = 0;
totalPoints = 0;
while ( quit != 'q' )
{
gamesPlayed++;
cout << "Welcome to Guessing Game! \n";
points = 5;
cout << "What would you like your range to be? \n";
cout << "Low number: \n";
cin >> rangeLow;
cout << "High number: \n";
cin >> rangeHigh;
if ( rangeLow > rangeHigh )
{
cout << "Please use a high number that is greater than the low number. \n";
cout << "Low number: \n";
cin >> rangeLow;
cout << "High number: \n";
cin >> rangeHigh;
}
else
{
;
}
computerNumber = rand( ) % (rangeLow - rangeHigh + 1) + 10;
cout << "Computer Number: " << computerNumber << endl;
cout << "Points:" << points << endl;
cout << "what is your guess? \n" << endl;
cin >> guess;
cout << "Your guess is: " << guess << endl;
When I input this code (among other error-free lines of code that don't affect these lines), it won't compile and outputs two error messages- "expression must have integral or unscoped enum type" and "'%' is illegal, right operand has type 'float'"
I have a feeling that it has something to do with using variables in my equation, but that shouldn't be a problem? All of the variable types are float that have to do with this equation, and I'm pretty confused.
%
is the modulus operator for integer values. Your range endpoints are floating point variables. In your exercise, you should make the endpoints, computerNumber
and guess
into int
variables.
int rangeLow, rangeHigh, computerNumber, guess;
Then take a look at the computer's number generator and insert some values to try it out:
computerNumber = rand() % (rangeLow - rangeHigh + 1) + 10;
rand() % ( 5 - 20 + 1) + 10;
rand() % -14 + 10;
So, you'll have rand() % -14 + 10
. That doesn't look correct. Reverse the range endpoints:
computerNumber = rand() % (rangeHigh - rangeLow + 1) + 10;
rand() % ( 20 - 5 + 1) + 10;
rand() % 16 + 10;
This, rand() % 16 + 10
, is better, but will obviously create a number in the range [10, 10+16)
, or to put it differently (as a closed interval), [10, 25]
. If you replace +10
with +rangeLow
like this:
computerNumber = rand() % (rangeHigh - rangeLow + 1) + rangeLow;
You now get the range like this:
[rangeLow, rangeLow + rangeHigh - rangeLow + 1) =>
[rangeLow, rangeHigh + 1) (left-closed interval) =>
[rangeLow, rangeHigh] (closed interval)
Which means [5, 20]
with the example values I used.
Now, take a look at <random>. That part of the standard library contains classes and functions to make all this much simpler: