Udostępnij za pośrednictwem


RAND

Generuje liczby pseudolosowe.Bardziej bezpieczna wersja ta funkcja jest dostępna, zobacz rand_s.

int rand( void );

Wartość zwracana

randZwraca liczby pseudolosowe, jak opisano powyżej.Istnieje bez powrotu błąd.

Uwagi

rand Funkcja zwraca pseudolosowe liczbą całkowitą z zakresu od 0 do RAND_MAX (32 767).Użyj srand — inicjuje funkcji do materiału siewnego generator liczby pseudolosowe przed wywoływaniem rand.

Wymagania

Rozpoczęto wykonywanie procedury

Wymaganego nagłówka

rand

<stdlib.h>

Aby uzyskać dodatkowe informacje o zgodności, zobacz zgodności we wprowadzeniu.

Przykład

// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//

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

void SimpleRandDemo( int n )
{
   // Print n random numbers.
   int i;
   for( i = 0; i < n; i++ )
      printf( "  %6d\n", rand() );
}

void RangedRandDemo( int range_min, int range_max, int n )
{
   // Generate random numbers in the half-closed interval
   // [range_min, range_max). In other words,
   // range_min <= random number < range_max
   int i;
   for ( i = 0; i < n; i++ )
   {
      int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
            + range_min;
      printf( "  %6d\n", u);
   }
}

int main( void )
{
   // Seed the random-number generator with the current time so that
   // the numbers will be different every time we run.
   srand( (unsigned)time( NULL ) );

   SimpleRandDemo( 10 );
   printf("\n");
   RangedRandDemo( -100, 100, 10 );
}
  

Odpowiednik w programie .NET Framework

Klasa System::Random

Zobacz też

Informacje

Wsparcie zmiennoprzecinkowe

srand — inicjuje

rand_s