I want to generate a random number between 31 to 60.
So i have used rand() but i think it will give some time same value.But i need ebvery time it should give me new value.
How can i do this?
Use arc4random(), it will provide a good random number and does not require seeding.
rand() will produce the same sequence each time the app is run unless you seed it with a unique value.
Then it is a matter or reducing the range. A simple solution is to mod to the range and add the low end of the range. (This will cause a small bias that should be acceptable.)
Example:
int rangeLow = 31;
int rangeHigh = 60;
int randomNumber = arc4random() % (rangeHigh-rangeLow+1) + rangeLow;
If what you want each number in the range to occur only once then @pawan.mangal has a link to a good solution.
Instead of rand() you can use arc4random()
To get an integer value from arc4random() that goes from 0 to x-1, you would do this:
int value = arc4random() % x;
To get an integer in the range 1 to x, just add 1:
int value = (arc4random() % x) + 1;
Finally, if you need to generate a floating point number, define this in your project:
#define ARC4RANDOM_MAX 0x100000000'
Then, you can use arc4random() to get a floating point value (at double the precision of using rand()), between 0 and 100, like so:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With