Page 1 of 1
Function to generate random within specific range
Posted: Thu Sep 15, 2016 8:47 am
by matteus
Code: Select all
u16 randomNumberGenerator(u16 finishInt) {
u16 x = 0;
do {
x = random();
} while (x <= 0 || x > finishInt);
return x - 1;
}
Is this the best way to be doing it?
u16 randomNumberGenerator(10) would give me random 1 to 10
Re: Function to generate random within specific range
Posted: Thu Sep 15, 2016 8:49 am
by cero
No, that's really wasteful, and can run infinite time. Hint: modulo operator.
Re: Function to generate random within specific range
Posted: Thu Sep 15, 2016 9:25 am
by matteus
Re: Function to generate random within specific range
Posted: Thu Sep 15, 2016 9:37 am
by matteus
P.S you've just helped me no end! I'm really grateful

Re: Function to generate random within specific range
Posted: Thu Sep 15, 2016 9:48 am
by cero
I would add a couple parenthesis (), otherwise the calculation order may not be what you expect.