rand

疑似乱数を生成します。 この関数のセキュリティが強化されたバージョンについては、「rand_s」を参照してください。

int rand( void );

戻り値

rand は疑似乱数を返します。 エラーの戻り値はありません。

解説

rand 関数は、0 ~ RAND_MAX (32767) の範囲の整数の擬似乱数を返します。 srand 関数を使用して、rand を呼び出す前に、擬似乱数ジェネレーターのシード値を指定します。

必要条件

ルーチン

必須ヘッダー

rand

<stdlib.h>

互換性の詳細については、「C ランタイム ライブラリ」の「互換性」を参照してください。

使用例

// 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 );
}
  

同等の .NET Framework 関数

System::Random Class

参照

参照

浮動小数点サポート

srand

rand_s