Random number generator help

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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <ctime>

using namespace 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";}
		else if (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 generate the random number before you initialize range:

num = rand() % range + 0; //range, at this point, is garbage
closed account (o3hC5Di1)
Hi there,

You need to initialize range to a number.
For examples, please see: http://www.cplusplus.com/reference/cstdlib/rand/?kw=rand

All the best,
NwN
Last edited on
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

using namespace 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.
Last edited on
Topic archived. No new replies allowed.