Random Number Generation

Hello I am new here and I have a problem... I have tried to write a random addition problem generator and my rand()'s always produce 8 for the first number and 2 for the second. I have looked into the basics of rand() number generation but nothing ive found is actually at the basic level. I hope this is not some completely simple mistake and apologize in advance if that is the case. Here is my code:

#include <iostream>
#include <stdlib.h>
#include <math.h>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

int addA;
int addB;
int sum;
int ans;

addA = rand () % 10+1;
addB = rand () % 10+1;

cout<< addA;
cout<< " ";
cout<< "+";
cout<< " ";
cout<< addB;
cout<< "Input answer";

cin>> ans;

sum = addA + addB;

if (sum == ans)
{ cout<< "ans is correct";
}
else
{
cout<< "ans is wrong";
}

return 0;
}
Use this :

srand(time(0));

More information here: http://www.cplusplus.com/reference/clibrary/cstdlib/srand/ .
Note you should only call srand once at the start of your program.

Do not put it before every single call to rand.
Wow OK and here i was raging over how every tutorial was about system time. Anyway is there any chance this is a new development because I did use c++ several years ago and I don't remember having to call srand. to generate a random number although I guess I could have just forgot that detail.

Oh and thanks, I will try your suggestions.
Last edited on
One note: While the inclusion of srand (time(0); is necessary,

you also need #include <time.h> which i did not have (to clarify for anyone who reads this having the same problem).

Anyway thanks again, program now runs as expected.

For anyone possibly interested, here is the final code:



#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <time.h>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

int addA;
int addB;
int sum;
int ans;

srand(time(0));

addA = rand () % 1000;
addB = rand () % 1000;

cout<< addA;
cout<< " ";
cout<< "+";
cout<< " ";
cout<< addB;
cout<< "\n";
cout<< "Input answer";
cout<< "\n";

cin>> ans;

sum = addA + addB;

if (sum == ans)
{ cout<< "ans is correct";
cout<< "\n";
}
else
{
cout<< "ans is wrong";
cout<< "\n";
}

system("PAUSE");

return 0;
}
Last edited on
Anyway is there any chance this is a new development


No. All pRNGs need to be seeded. There was never a time when rand() automatically seeded itself.
Topic archived. No new replies allowed.