Problem with functions

Hey,
I am using a function in a code, but i want to use it multiple time. However my problem is that it returns the same value for each thing i use it for... any advice?

My code is:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cstdlib>
#include <ctime>

int statgen();

int main()
{
	srand((unsigned)time(0)); 
	int str, con, dex, inl, wis, cha;
	str = statgen();
	con = statgen();
	dex = statgen();
	inl = statgen();
	wis = statgen();
	cha = statgen();
	std::cout << "STR is " << str << "\n";
	std::cout << "CON is " << con << "\n";
	std::cout << "DEX is " << dex << "\n";
	std::cout << "INT is " << inl << "\n";
	std::cout << "WIS is " << wis << "\n";
	std::cout << "CHA is " << cha << "\n";
	
	return 0;
}
	
int statgen()
{
	// defining my variables and giving my random a seed
	srand((unsigned)time(0)); 
	int d1, d2, d3, d4, sum;
	d1 = rand() % 6+1;
	d2 = rand() % 6+1;
	d3 = rand() % 6+1;
	d4 = rand() % 6+1;
	

	// sets the lowest number to 0 so that the stat isnt above 18
	if (d1<=d2 && d1<=d3 && d1<=d4)
		d1 = 0;
	if (d2<=d1 && d2<=d3 && d2<=d4)
		d2 = 0;
	if (d3<=d1 && d3<=d2 && d3<=d4)
		d3 = 0;
	if (d4<=d1 && d4<=d2 && d4<=d3)
		d4 = 0;
	
	//sets the sum equal to all the dice including the 0
	sum = d1+d2+d3+d4;

	return sum;	
	}
Call srand() only once in your program.
should i only call it in statgen() or in main()?
and also could you explain how it helps?
only call srand in the function, the function ig generating the random numbers and assigning it to each value u have in main.
Read up on pseudo random number generation. rand returns numbers in a constant sequence. srand sets where in that sequence you begin.
That is, if you do srand(0), and then call rand() any number of times, every time you run the program, rand() will generate the same numbers. The randomness comes from what you put in srand(). Usually it is time. The problem here is that the time at line 11 is the same as the time at line 16, so you call srand() several times with the same value and thus rand() returns same values.
Technically it doesn't matter where you call srand() as long as it is before any rand() and only once. Since you already have it called on line 9, erase line 30.
Topic archived. No new replies allowed.