What is the standard library function returns a random integer within a specified range of values?

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

Min + (int)(Math.random() * ((Max - Min) + 1))

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

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.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

Min + (Math.random() * (Max - Min))

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

5 + (Math.random() * (10 - 5))

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

Min + (int)(Math.random() * ((Max - Min) + 1))

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))

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.

rand

  • Article
  • 09/19/2022
  • 2 minutes to read

In this article

Generates a pseudorandom number. A more programmatically secure version of this function is available; see rand_s. Numbers generated by rand aren't cryptographically secure. For more cryptographically secure random number generation, use rand_s or the functions declared in the C++ Standard Library in <random>.

Syntax

int rand(void);

Return Value

rand returns a pseudorandom number, as described above. There's no error return.

Remarks

The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767). Use the srand function to seed the pseudorandom-number generator before calling rand.

The rand function generates a well-known sequence and isn't appropriate for use as a cryptographic function. For more cryptographically secure random number generation, use rand_s or the functions declared in the C++ Standard Library in <random>.

By default, this function's global state is scoped to the application. To change this, see Global state in the CRT.

Requirements

RoutineRequired 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

Which function returns a random integer quizlet?

The rand() function, in the C standard library, returns a random integer each time the function is called, in the range 0 to RAND_MAX.

What is a library function quizlet?

Library Function. This term describes any mechanism that accepts input, performs some operation. that cannot be seen on the input, and produces output.

Which of the following function returns the largest integer that is less than or equal to its argument?

Description. The floor() function calculates the largest integer that is less than or equal to x.

Which type of function returns either true or false?

A Boolean expression is a logical statement that is either TRUE or FALSE . Boolean expressions can compare data of any type as long as both parts of the expression have the same basic data type.