I have written a simple random number generator in C. Int l is the lower bound & int u is the upper bound.

Bạn đang xem: C

It works just fine, however I have a question regarding seeding it. If I was to run this in a loop, time(NULL) doesn"t change the seed value quick enough khổng lồ be able to lớn prevent getting a consecutive series of random numbers that are exactly the same.

I"m wondering how anybody else might have approached this problem. All the examples I"ve found online use time(NULL) as the seed value generator.

int generateRandom(int l, int u) srand(time(NULL)); int r = rand() % ((u - l) + 1); r = l + r; return r;If I was lớn run these lines of code right next lớn each other, both Rand1 & Rand2 would be exactly the same.

printf("Rand1 = %d ", generateRandom(10, 46));printf("Rand2 = %d ", generateRandom(10, 46));
asked Apr 7, 2011 at 1:29


7,56699 gold badges6161 silver badges9595 bronze badges
địa chỉ cửa hàng a comment |

6 Answers 6

Sorted by: Reset to default
Trending sort available
Introducing: Trending sort You can now choose to sort by Trending
, which boosts votes that have happened recently, helping to lớn surface more up-to-date answers.

Xem thêm: Chữ Cái Tiếng Việt Có Bao Nhiêu Chữ, Tiếng Việt Có Bao Nhiêu Chữ Cái

Trending is based off of the highest score sort & falls back khổng lồ it if no posts are trending.

Try it Dismiss
Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
srand(time(NULL)) should be run exactly once lớn intialise the PRNG. Bởi vì this in Main when the application starts.


A PRNG (Pseudo-Random Number Generator) generates a deterministic sequence of numbers dependent on the algorithm used. A given algorithm will always produce the same sequence from a given starting point (seed). If you don"t explicitly seed the PRNG then it will usually start from the same mặc định seed every time an application is run, resulting in the same sequence of numbers being used.

Xem thêm: Định Luật Bảo Toàn Momen Động Lượng, Mô Men Động Lượng

To fix this you need to lớn seed the PRNG yourself with a different seed (to give a different sequence) each time the application is run. The usual approach is to lớn use time(NULL) which sets the seed based on the current time. As long as you don"t start two instances of the application within a second of each other, you"ll be guaranteed a different random sequence.

There"s no need to lớn seed the sequence each time you want a new random number. Và I"m not sure about this, but I have the feeling that depending on the PRNG algorithm being used re-seeding for every new number may actually result in lower randomness in the resulting sequence.