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

后端 未结 4 969
小蘑菇
小蘑菇 2021-01-26 01:13

Looking to make a really simple random number generator method in C. The numbers should be between 0 and 24 and can be for example 14.5f.

Any help would be great, thanks

相关标签:
4条回答
  • 2021-01-26 01:38
    float getRand() {
      float rnd = rand();
      rnd /= RAND_MAX;
      return rnd * 24.0f;
    }
    

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

    0 讨论(0)
  • 2021-01-26 01:43

    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.

    0 讨论(0)
  • 2021-01-26 01:48

    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.)

    0 讨论(0)
  • 2021-01-26 01:48

    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.

    0 讨论(0)
提交回复
热议问题