# random number generation

Hi,
Can I please get a C code for generating  a random number that is uniformly distributed in the range[8,32].
Thanks.
Programming

Last Comment
CleanupPing

8/22/2022 - Mon
Gula

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
luisseixas

I don't know about C but, check this Delphi code out. Maybe you can get some ideas.

First, somewhere in your project, you start then built-in random number generator:

procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
end;

The "Random" function gives you a number 0 <= N < 1. Just do something like this:

procedure TForm1.ButtonClick(Sender: TObject);
const Upper=32;
Lower=8;
var   Number: Integer;
begin
Number:=Trunc(Random*(Upper-Lower+1))+Lower;
end;

Easy!
Leo71

For Windows, MS VC I would suggest:

#include <stdlib.h>
#include <time.h>

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

(rand()*(32-8))/RAND_MAX+8;

srand with time is because otherwise you programm starts everytime with the same sequence of random numbers.

If you search for a code to implement you own random numbe generator I can't help you.

Regards
Leo
d34thk

mmhmm...

use

srand(time(NULL));
rand()%x+y;

i cant remember how the x and y works, but if u work it out, it makes the random number be between them.

i think the minimum random number is x, while the maximum is x+y (add them together)

so 1+2 would give u a random number between 1 and 3

correct me if im wrong
Leo71

you mean srand()%(32-8 +1)+8, I guess :), like Gula said.

With other words: srand()%(Range+1)+startvalue
which works as long fine, as Range < RAND_MAX.

My solution ((rand()*Range)/RAND_MAX+startvalue can blow up the values over RAND_MAX, but the resolution still sticks at RAND_MAX.
But one could multiply two random numbers, if a higher range+resolution is needed.... ;-).

Regards
Leo
CleanupPing

bujji71: