Convert C code to Delphi -- random function

P

Peter Williams

Hi All,

I need to port the following (small) C language function to Delphi:

double Rand(void) {
return rand()/(1.0 + (double)RAND_MAX);
}

NB -- elsewhere in the program randomize is called before-hand.

I don't know what (exactly) the C language function "rand()" does.
Also, RAND_MAX is not defined anywhere in the program, so is it part of
C ???

My attempt at starting to write it in Delphi:

function Rand : Real;
begin
Result := ????????????????
end;

NB -- Delphi has a Random(N) function which takes an integer (N) as
it's parameter and returns an integer in the range 0..N-1 . E.g.
Random(3) would return either 0, 1, or 2.

NB(2) -- Obviously, Delphi also has a "randomize" function which I am
aware I need to call first.

Can anyone please assist me in writing this routine as a Delphi code
snippet???

Any help will be greatly appreciated. :)

Regards,
Peter W. :)))
Sandy Bay, Hobart, Tas, AU.
 
K

Keith Thompson

Peter Williams said:
I need to port the following (small) C language function to Delphi:

double Rand(void) {
return rand()/(1.0 + (double)RAND_MAX);
}

NB -- elsewhere in the program randomize is called before-hand.

I don't know what (exactly) the C language function "rand()" does.
Also, RAND_MAX is not defined anywhere in the program, so is it part of
C ???

You should be able to find this information in any C textbook or in
your system's documentation, but ...

The rand() function returns a pseudo-random integer in the range 0 to
RAND_MAX.

RAND_MAX is an integer constant defined in <stdlib.h>; its value will
vary from one implementation to another, but it's guaranteed to be at
least 32767.

srand() seeds the random number generator. A given seed will produce
a repeatable sequence of numbers from rand(). If you don't call
srand(), it's equivalent to calling it with a seed value of 1.

The function appears to be attempting to generate a random double
(floating-point) number in the range 0.0 to 1.0, with the upper bound
excluded.

You might take a look at section 13 of the C FAQ,
My attempt at starting to write it in Delphi:
[snip]

Good luck with the Delphi part; we can't help you with it here.
 
P

pete

The function appears to be attempting to generate a random double
(floating-point) number in the range 0.0 to 1.0, with the upper bound
excluded.

And the cast is superfluous.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top