How to do random in C?

  • Videogamer555
    19th Jan 2012 Member 0 Permalink
    I want to know how to do random numbers in C. Is there a specific random command? Is it math.random like in Lua?
  • Neospector
    19th Jan 2012 Member 0 Permalink
    rand()%PERCENTAGE OF RANDOMIZATION

    So, the code:


    else if ((r&0xFF)==PT_GUNP && 15>(rand()%1000))
    part_change_type(r>>8,x+rx,y+ry,PT_DUST);

    Within neut.c will always turn the GUNP to DUST on contact with NEUT.
  • Pilihp64
    19th Jan 2012 Developer 0 Permalink
    @Neospector (View Post)
    well, not exactly, that number is not a percentage.
    the % symbol in C is the modulus operator, which divides a number but returns the remainder, and not the result.
    4%100 is 4, 106%100 is 6.
    the rand() function picks a random number 0-rand_max(a very high number) , using % with that ends up getting you a number bewteen 0-x , x being the number you use, 1000 in that example. Which is then being compared to 15, so in that case, it has a 15/1000 chance to become DUST.
  • abczyx123987
    19th Jan 2012 Member 0 Permalink
    @cracker64 (View Post)
    rand() gives you a random number from 0 - RAND_MAX (which is dependent on the compiler -- it's 32767 on mine).
    (Just saying....)
  • Neospector
    19th Jan 2012 Member 0 Permalink
    @cracker64 (View Post)
    Oh, I see. Still the same principle, however, correct?
  • Videogamer555
    19th Jan 2012 Member 0 Permalink
    Does Rand always give an integer value or does it sometimes give a value with decimal (float or double type value) like 5.43582?
  • abczyx123987
    19th Jan 2012 Member 0 Permalink
    @Videogamer555 (View Post)
    It's always an integer.
    Basically, it's declared in stdlib.h like
    int rand(void);So it'll always return an integer. (from 0 - RAND_MAX).