Note that this approach is more biased and less efficient than a Show One standard pattern for accomplishing this is:
The Java Math library function Math.random() generates a double value in the range In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
This returns a value in the range For example, if you want
This would return a value in the range Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
You now will get a value in the range
But, this still doesn't include
And there you have it. A random integer value in the
range Skip to main content This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
|
Routine | Required header |
---|---|
rand
| <stdlib.h>
|
For more compatibility information, see Compatibility.
Example
// crt_rand.c
// This program seeds the random-number generator
// with a fixed seed, then exercises the rand function
// to demonstrate generating random numbers, and
// random numbers in a specified range.
#include <stdlib.h> // rand(), srand()
#include <stdio.h> // printf()
void SimpleRandDemo(int n)
{
// Print n random numbers.
for (int i = 0; i < n; i++)
{
printf(" %6d\n", rand());
}
}
void RangedRandDemo(int range_min, int range_max, int n)
{
// Generate random numbers in the interval [range_min, range_max], inclusive.
for (int i = 0; i < n; i++)
{
// Note: This method of generating random numbers in a range isn't suitable for
// applications that require high quality random numbers.
// rand() has a small output range [0,32767], making it unsuitable for
// generating random numbers across a large range using the method below.
// The approach below also may result in a non-uniform distribution.
// More robust random number functionality is available in the C++ <random> header.
// See https://learn.microsoft.com/cpp/standard-library/random
int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
printf(" %6d\n", r);
}
}
int main(void)
{
// Seed the random-number generator with a fixed seed so that
// the numbers will be the same every time we run.
srand(1792);
printf("Simple random number demo ====\n\n");
SimpleRandDemo(10);
printf("\nRandom number in a range demo ====\n\n");
RangedRandDemo(-100, 100, 100000);
}```
```Output
Simple random number demo ====
5890
1279
19497
1207
11420
3377
15317
29489
9716
23323
Random number in a range demo ====
-82
-46
50
77
-47
32
76
-13
-58
90
See also
Floating-Point Support
srand
rand_s
C++ <random>
library
Feedback
Submit and view feedback for