-3

I'm working on a program that uses a function that would generate 2 random integers that I would later use to ask the user to add and figure out the sum. For the time being, I came across a problem in which it's duplicating the same number.

Here's the program thus far:

#include<iostream>
#include<ctime>
using namespace std;


/*
This function generates a random integer
between 0 and max_int
*/
int get_rand_int(int max_int){
    srand(time(0));
    return int(rand()) % max_int;
}


This program generates random addition problems
with integers between 0 and 100


int main(){
    int num1 = get_rand_int(101);
    int num2 = get_rand_int(101);
    cout << num1 << endl;
    cout << num2 << endl;

Please note this this is a homework problem my teacher assigned. He provided us with the skeleton and we're trying to fill in the blanks. I have a feeling the problem lies within the srand section of my function but that was part of my teacher's work so I'm not sure whether I need to touch that. Thanks in advance.

trungnt
  • 1,111
  • 1
  • 7
  • 19
  • You *know* this has been asked before... – Eric J. Apr 24 '15 at 03:56
  • @EricJ.: While I agree, the link you've provided is about C#. A better choice might be http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once – Bill Lynch Apr 24 '15 at 03:58
  • Same exact issue. Most languages in fact share this issue. Feel free to vote to close as a duplicate of the one you provide though. – Eric J. Apr 24 '15 at 04:00
  • I apologize that this might be a duplicate question. I read those other questions and saw how srand is the issue. I just want to make sure that's the only problem with it duplicating since my professor was the one that provided that srand in the skeleton program. – trungnt Apr 24 '15 at 04:09

3 Answers3

4

Yes. srand initializes the random sequence with the result of time. However, time changes only once per second! This means that if you call your function twice in a one-second delay, you get the same number.

One solution is to call srand just once, at the beginning of your program (in the main function, for instance).

zneak
  • 134,922
  • 42
  • 253
  • 328
2

You must seed the random generator only once in your program,

srand(time(0)); // this must happen only once, at the beginning of main()

You now seed it inside the function get_rand_int, and call the function twice in a very short amount of time. The seed ends up being the same, so you get the same sequence of numbers.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

Call the srand(time(0)) in the main to set the current time only once to use random generation instantly.

int main(){
srand(time(0));
int num1 = get_rand_int(101);                          
int num2 = get_rand_int(101);
cout << num1 << endl;
cout << num2 << endl;

}

scho852
  • 11
  • 2