Easy to solve problem about rand()

Dec 30, 2012 at 4:48pm
Why does this give me the same number every time? ie: 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string fnRandom()
{
    srand(NULL);
    int nTemp;

    nTemp=rand()%9+1;
    if(nTemp==1) {return "A1";}
    if(nTemp==2) {return "B1";}
    if(nTemp==3) {return "C1";}
    if(nTemp==4) {return "A2";}
    if(nTemp==5) {return "B2";}
    if(nTemp==6) {return "C2";}
    if(nTemp==7) {return "A3";}
    if(nTemp==8) {return "B3";}
    if(nTemp==9) {return "C3";}

    return "0";
}


Aceix.
Last edited on Dec 30, 2012 at 4:52pm
Dec 30, 2012 at 4:49pm
Because you use the same seed each time.
Dec 30, 2012 at 4:52pm
Never mind. Problem SOLVED!!!

Soln:
srand(time(NULL));

Thanks for trying to help,
Aceix.
Dec 30, 2012 at 5:09pm
Note you should NOT call srand in this function at all.

You should call srand() exactly once when the program starts. You must not call it every time you generate a new random number.
Dec 31, 2012 at 5:57pm
Disch, why do you advise against calling srand() whenever you generate a random number? I am guilty of doing this in many of my programs, and I am curious as to why it is considered bad practice.
Dec 31, 2012 at 6:03pm
1. Because it's a waste of performance.
2. Because it's not needed.
3. Because it's just a risk of non-randomness in certain cases.

So: Just stick with what Disch said, Just call srand() once, unless you need to reproduce a bug (eg if a bug is rand-dependent, in Debug mode you may want to call srand ~once~ with a specific number so you can reproduce and debug the bug) or you don't need complete randomness.
Dec 31, 2012 at 6:30pm
Thanks for your help! It makes sense that it is not needed to call srand() too many times.
Topic archived. No new replies allowed.