Hello, below is my code for a HiLo game program. It works great, but my random number generator always gives the same number? Anytime I try playing the game, the "random number" is zero. What am I doing wrong?
#include <iostream>
#include <ctime>
usingnamespace std;
int main ()
{
int range;
int num = 0;
int guess = 0;
int tries = 0;
srand(time(0));
num = rand() % range + 0;
cout << "Hello! Welcome to the HiLo game!" << endl;
cout << "To start, please enter the range: ";
cin >> range;
do
{
cout << "Enter a guess between 0 and "<<range<<":";
cin >> guess;
tries++;
if (guess > num)
{cout << "Too high, try again!\n\n";}
elseif (guess < num)
{cout << "Too low, try again!\n\n";}
else
{cout << "\nCorrect! It took you " << tries << " tries!\n";}
if ( guess == -999)
{cout << "The correct number was:" << num << endl;}
} while (guess != num);
system("pause");
}
You can always use a specifically designed function to aid with random numbers, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <cstdlib>//required for rand function
#include <iostream>//required for cout function
#include <ctime>//required for time function
usingnamespace std;
int random(int low,int high)
{
return rand()%(high-low+1)+low;
}
int main()
{
srand(time(NULL));//set random number seed
num=random(1,10);//assign variable a random number between 1 and 10
cout<<num;//outputs the random number generated
return 0;
}
Anytime you need a random number, or need to make an existing variable a random value, random(lowest,highest) can be used.