Dump using the C library random functions, they are outdated. Even the C standard recommends not using rand() and srand().
The C++ library has much better random number generation engines and distributions:
http://www.cplusplus.com/reference/random/
(Examples galore for how to use the class templates)
With that said, try changing your current logic to look for a zero or negative number as the input to break out of your game loop.
Also move your srand() function above the start of your game loop, it should only be run once, before you start generating random numbers.
Note, line 27, you are assigning true to the game variable, which will always be evaluated as true, not checking for equality (==).
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
|
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
while (true)
{
cout << "Enter a number, or Enter 0 or less to exit the program: ";
int max;
cin >> max;
if (max <= 0)
{
break;
}
int random_number = (rand() % max) + 1;
cout << random_number << endl;
}
system("pause");
return 0;
}
|