views:

66

answers:

1

int randomNumber = (double)rand() / (RAND_MAX + 1) * (10 - 0) + 0;

is the code I'm using, it is getting a random number, but is getting the SAME random combination every time?

Can anyone see what I'm doing wrong?

+6  A: 

Try to seed it with a different value each time.

srand(time(0))
N 1.1
`srand(getpid())` can also be used. you need to include `ctime` for `time()`
N 1.1
@N or arguably better-yet, `srand(time(0)^getpid())`.
wilhelmtell
They say `srand(time(0))` will do for most cases, but sometimes it isn't good enough. For example, if you write a standard Unix commandline tool where your application starts and (often) quits relatively fast then you need a more sophisticated seed. To see the problem, in Bash try something like the following: `for i in $(seq 10); do ./a.out; done` (where `a.out` is your executable's name). You will see you (most of the times) get the same value. The reason is that the shell executes the program (10 times) so fast that the program gets the same seed for `time(0)`.
wilhelmtell
So one solution in this case would be like @N suggests, to use `getpid()` from the `unistd.h` header. On Windows I think it's `_getpid()` from the `process.h` header. Another approach is to read a byte from /dev/urandom on Unix; in Windows you'd need to jump through a number hoops to get this random functionality. The former approach is much simpler and should get the job done. The latter approach is theoretically more solid but is more sophisticated, especially if you cross-compile between Windows and Unix.
wilhelmtell