Login
Username:

Password:

Remember me



Lost Password?

Register now!

Sections

Who's Online
120 user(s) are online (81 user(s) are browsing Forums)

Members: 1
Guests: 119

VooDoo, more...

Headlines

 
  Register To Post  

C / Random Value
Quite a regular
Quite a regular


See User information
Hi All,

I've seen that I can use rand() or srand() to generate randoms numbers but I don't understand how I can exactly set a limit to rand value.

For exemple, I want to get a random number between 0 - 640 ...

I can I proceed ?

I tried to create this function :

int Rndint RangeValue ){
  
float NewRandom = (float)( rand() & 0x7FFFFFFF );
  
float NewFACTOR = (float)( RangeValue 2147483647 ) ; // 2147483647 = 0x7FFFFFFF
  
NewRANDOM NewRANDOM NewFACTOR;
  return (int)
NewRANDOM;
 }


Thank you.


Edited by freddix on 2009/3/9 22:16:16
All we have to decide is what to do with the time that is given to us.
Go to top
Re: C / Random Value
Just popping in
Just popping in


See User information
@freddix

Hi!

All You need is "%" modulo division, ex
int rangedValue = value % range;

Go to top
Re: C / Random Value
Quite a regular
Quite a regular


See User information
@Radov
I'm sorry but I don't understand what you mean ...

All we have to decide is what to do with the time that is given to us.
Go to top
Re: C / Random Value
Not too shy to talk
Not too shy to talk


See User information
@freddix

Quote:

For exemple, I want to get a random number between 0 - 640 ...



#define rnd(lo,hi) ((rand() % ((hi) - (lo) + 1)) + (lo))


Bye,
Thomas

Go to top
Re: C / Random Value
Just popping in
Just popping in


See User information
@freddix

Hi,

reading the C manual, you can see that rand returns a pseudo number between 0 and RAND_MAX.

So to have a number between 0 and 640, you can do this :

A = rand();

A = A- 640 * int(A/640) ; // A = A modulo 640.

But I suggest you to use other algorithm like md5.
You will have a better random number generator.

Hope that this can help you.

Go to top
Re: C / Random Value
Quite a regular
Quite a regular


See User information
@yescop
Thank you for these informations.

It now work perfectly :)

Regards,
AmiDARK.

All we have to decide is what to do with the time that is given to us.
Go to top

  Register To Post

 




Currently Active Users Viewing This Thread: 1 ( 0 members and 1 Anonymous Users )




Powered by XOOPS 2.0 © 2001-2023 The XOOPS Project