0

So I'm generating some random numbers. I'm using

srand(time(NULL));

to generate random numbers. However I have this within a for loop. Im generating 10 'sets' of random numbers, but they are all the same. I was wondering how I could change this line of code to ensure the random numbers each time the program goes round the loop.

bgrantham
  • 281
  • 4
  • 12
  • This simply sets the random number generator seed. You need an additional call to `rand` to produce a random number. – Fiddling Bits Mar 26 '15 at 17:50
  • 3
    "I have this within a for loop" - that's your mistake. This should execute *once* in your program, ideally near the head of `main()`. – WhozCraig Mar 26 '15 at 17:50
  • @simonc @ WhozCraig Thank you. It has fixed the problem straight away. For some reason I had it in my head that it needed to set a new seed at the start of each loop. – bgrantham Mar 26 '15 at 17:53
  • @user2996994 This would work if the value `time(NULL)` returned was different every loop. – Fiddling Bits Mar 26 '15 at 17:57
  • srand might be called only once. It's used to initialize the seed of pseudorandom numbers, as you call it ten times in a loop in the same second (you call 10 times time() returning the same time value, you are initializing ten times the random generator with the same value, so you'll get the same sequence of numbers from each initialization) – Luis Colorado Mar 27 '15 at 06:08

1 Answers1

1

Already answerd : What you'll want to do is call srand() once, when the program starts (at the start of your main() function) Then call rand() every time you want a random number

srand function is returning same values

Community
  • 1
  • 1
Salim Mahboubi
  • 561
  • 7
  • 25