Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking random number between two points in C

Tags:

c

random

I was wondering, is it possible to generate a random number between two limits in c. I.e. my program is set like this:

function x
{
    generate random number;
}

while(1)
{
    function x;
    delay
}

so bascially I want a random number to be generated everytime the function is called , but the number has to be between, for example, 100 and 800

I know there is a already made function called random and randmize in stdlib.h I just dont know how to create the upper and lower limits

Thank you

like image 530
user1175889 Avatar asked Jan 17 '23 07:01

user1175889


1 Answers

First, don't forget to seed your PRNG once and only once:

srand(time(NULL));

Then, this function should do what you want.
(lightly tested, seems to work)

int RandRange(int Min, int Max)
{
    int diff = Max-Min;
    return (int) (((double)(diff+1)/RAND_MAX) * rand() + Min);
}

In your case, you'll want to:

x = RandRange(100, 800);  /* x will be between 100 and 800, inclusive */

This uses floating-point math, which may be slower than modulo (%) arithmetic, but will have less bias.

like image 163
abelenky Avatar answered Jan 28 '23 01:01

abelenky