Exportar (0) Imprimir
Expandir todo
div
eof
Expandir Minimizar

rand_s

Generates a pseudorandom number. A version of rand with security enhancements as described in Security Enhancements in the CRT.


errno_t rand_s(   unsigned int* randomValue);

Zero if successful, otherwise an error code. If the input pointer randomValue is a null pointer, the function invokes an invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, the function returns EINVAL and sets errno to EINVAL.

The rand_s function writes a pseudorandom integer in the range 0 to UINT_MAX to the input pointer. The rand_s function uses the operating system to generate cryptographically secure random numbers. It does not use the seed generated by the srand function nor does it affect the random number sequence used by rand.

The rand_s function requires that constant _CRT_RAND_S be defined prior to the inclusion statement in order for the function to be declared, such as in the example below:

#define _CRT_RAND_S
#include <stdlib.h>

Routine Required header Compatibility

rand_s

<stdlib.h>

Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

For additional compatibility information, see Compatibility in the Introduction.

// crt_rand_s.c
// This program illustrates how to generate random
// integer or floating point numbers in a specified range.

// Remembing to define _CRT_RAND_S prior
// to inclusion statement
#define _CRT_RAND_S

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

int main( void )
{
    int             i;
    unsigned int    number;
    double          max = 100.0;
    errno_t         err;

    // Display 10 random integers in the range [ 1,10 ].
    for( i = 0; i < 10;i++ )
    {
        err = rand_s( &number );
        if (err != 0)
        {
            printf("The rand_s function failed!\n");
        }
        printf( "  %u\n", (unsigned int) ((double)number /
                          (double) UINT_MAX * 10.0) + 1);
    }

    printf("\n");

    // Display 10 random doubles between 0 and max
    for (i = 0; i < 10;i++ )
    {
        err = rand_s( &number );
        if (err != 0)
        {
            printf("The rand_s function failed!\n");
        }
        printf( "  %g\n", (double) number / 
                          (double) UINT_MAX * max );
    }
}

10
  4
  5
  2
  8
  2
  5
  6
  1
  1

  32.6617
  29.4471
  11.5413
  6.41924
  20.711
  60.2878
  61.0094
  20.1222
  80.9192
  65.0712

Adiciones de comunidad

AGREGAR
Mostrar:
© 2014 Microsoft