Generate random number in a range [0, n) in C?

天大地大妈咪最大 提交于 2019-12-02 10:59:41
float getRand() {
  float rnd = rand();
  rnd /= RAND_MAX;
  return rnd * 24.0f;
}

Make sure you seed the random number generator with srand before use.

The Mersenne_twister is not only very simple, but also very strong.

See the code on the link.

However, if you can use GPL License, use the The GNU Scientific Library (GSL) specific check Random-Number-Generator-Examples from Random-Number-Generation part of the manual

There are many things there, from simple uniform random numbers to other distributions.

Have a look at linear congruential generators, they are quite simple to implement even with my inferior math knowledge.

Looks like I misunderstood the original question, I thought you wanted to roll your own generator (for homework, fun etc.)

You can use C's built in random number generator to get an integer between 0 and 30 thousand something like this:

`srand(time(NULL));
    int x= rand();`

You would just need to do some division to get a decimal number instead of and integer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!