Srand() isn't helping me with the Random Number Gen
Jul 17, 2013 at 4:44am UTC
Hi,
So, I'm pretty new to C++ and I'm trying to make a simple command line game, if you will, that lets you add a pair of random numbers anywhere from 1-1000. The problem is, even though I seeded the generator time(NULL), the same numbers are constantly being generated.
I've played around with this for so long but I just can't figure out how to get it to work (which is also why the code may not be as efficient as it could be). So if anyone can help me figure out why it won't work, thanks in advance.
Using MS Visual Studio 2010.
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 35 36 37 38
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int a = rand() % 1001;
int b = rand() % 1001;
int c = a + b;
int x;
void reVal();
void echo();
int main() {
srand(time(NULL));
echo();
return 0;
}
void echo() {
cout << a << " +\n" << b << "\n" ;
cin >> x;
if (x == c) {
cout << "Correct!\n\n" ;
reVal();
echo(); }
else {
cout << "Wrong.\n\n" ;
echo(); }
}
void reVal() {
int a = rand() % 1001;
int b = rand() % 1001; }
Jul 17, 2013 at 5:12am UTC
1 2 3 4 5 6
void reVal()
{
a = rand() % 1001;
b = rand() % 1001;
c = a+b ;
}
a and
b in
reVal were local variables completely different than the global variables
a and
b .
c will also not update itself.
Consider an alternative without endless recursion or global variables:
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 35
#include <iostream>
#include <cstdlib>
#include <ctime>
int getGuess(int a, int b)
{
std::cout << a << " + " << b << " = " ;
int answer = -1;
std::cin >> answer ;
return answer ;
}
int main()
{
std::srand(std::time(0)) ;
const int limit = 1001 ;
int a = rand() % limit ;
int b = rand() % limit ;
int answer ;
while ( (answer = getGuess(a,b)) >= 0 )
{
if ( answer == a+b )
{
std::cout << "Correct!\n\n" ;
a = rand() % limit ;
b = rand() % limit ;
}
else
std::cout << "Incorrect!\n\n" ;
}
}
Jul 17, 2013 at 5:43am UTC
Geez, that's a little embarrassing...
Thanks, really helped.
Topic archived. No new replies allowed.