rand() help required.

Hello.
I need to make a random number generator for numbers between 1 and 3.
I also need to do this using srand and rand in two separate functions.
My issue is, the srand needs to be in a non-returning function.

1
2
3
4
5
6
7
8
9
10
11
void set_seed()
{
	time_t t;
	time (&t);
	srand (time(0));
}

int get_number()
{
	return (rand()%3+1);
}


When I do this the rand doesn't seem to pick up the seed from the srand function, and just outputs the same numbers constantly.
When I change the void to an int, it seems to work great.
Am I doing something wrong here? I don't understand why it's refusing to work. :(

Thanks in advance for any help.

EDIT: Good news everyone! This function now no longer works as an int. D:
Last edited on
You should only be calling set_seed once at the start of your program. You should not be calling it for every generated number.

Something else unrelated:

1
2
3
4
5
6
void set_seed()
{
//	time_t t;   // these two lines are pointless.  Why fill 't'
//	time (&t);  //  if you're just discarding it?
	srand (time(0));
}
They are two separate functions outside of the main function.
set_seed is only being called once, but it seems to be ignored for no adequate reason.

Also, the pointless lines are because I have no idea how this function works, and I'm basically just copy-pasting all the different forms of time seed until I get one that works.
No success.
Last edited on
Post a program that exhibits that behavior; if you call srand(), then calling rand() afterwards ought to work fine.
+1 Zhuge.

This code, for example, should work. You can try it for yourself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void set_seed()
{
  srand(time(0));
}

int get_number()
{
  return (rand()%3+1);
}

int main()
{
  set_seed();

  for(int i = 0; i < 10; ++i)
    cout << get_number() << endl;
}
Topic archived. No new replies allowed.