C プログラミング言語の rand() 関数は、擬似乱数を生成するために使用されます。 C では、0 ~ RAND_MAX の範囲の乱数を生成するために使用されます。
rand() 関数は標準 C ライブラリの一部です。 したがって、この関数を使用するには、ライブラリをインクルードする必要があります。
rand()の構文
int rand (void)>
パラメーター
- この関数はパラメータを受け取りません。
戻り値
- この関数は、0 から RAND_MAX までの値を返します。RAND_MAX は、ライブラリで定義されているマクロです。
注記: rand() 関数は、デフォルトで値 1 をシードとして使用して乱数を生成し、同じ乱数シーケンスが生成されます。これを防ぐには、次のようにします。 スランド() rand() 関数の新しいシードを指定する関数。
C での rand() の例
例 1: rand() 関数の図
C
HTMLからJavaScript呼び出し関数
// C program to illustrate the use of rand() function> #include> #include> > int> main()> {> >// Generate a random number using the rand() function> >int> value =>rand>();> > >// Print the generated random value> >printf>(>'The Random Value is: %d'>, value);> > >return> 0;> }> |
>
>出力
The Random Value is: 1804289383>
時間計算量 :O(1)
空間の複雑さ: ○(1)
例 2: 10 個の乱数を生成する
C
完全な形で
// C program to generate 10 random number using rand()> // function> #include> #include> > int> main()> {> >int> i = 0;> >// Loop through 10 times> >for> (; i <10; i++) {> >// Generate a random number using the rand()> >// function> >int> value =>rand>();> > >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }> |
>
>出力
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421>
ただし、0 から N の範囲の乱数を生成したい場合は、 rand() 関数によって生成された数値の (N+1) の剰余を出力して変更する必要があります。
例: N より小さい乱数を生成する
C
// C program to generate random numbers smaller than a> // particular number n> #include> #include> int> main()> {> >// Set a constant 'N' to 1000> >int> N = 1000;> > >// Loop through 10 times> >for> (>int> i = 0; i <10; i++) {> >// Generate a random number between 0 and N using> >// the rand() function> >int> value =>rand>() % (N + 1);> >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }> |
>
>出力
897 802 765 992 1 521 220 380 729 969>
このようにして、0からNまでの乱数を簡単に生成することができます。
また、次の間に存在する乱数が必要な場合は、 下限 そして 上界 これは、 rand() 関数によって生成された乱数に簡単な数学を使用することで実行できます。
例: 範囲内の乱数を生成する
C
// C program to illustrate how to generate random number> // withing a range> #include> #include> int> main()> {> >// Set the upper bound for random numbers> >int> upper_bound = 1000;> >// Set the lower bound for random numbers> >int> lower_bound = 100;> > >// Loop through 10 times> >for> (>int> i = 0; i <10; i++) {> >// Generate a random number within the specified> >// bounds> >int> value =>rand>() % (upper_bound - lower_bound + 1)> >+ lower_bound;> >// Print the generated random value> >printf>(>'%d '>, value);> >}> > >return> 0;> }> |
>
スピーカーとは何ですか
>出力
943 897 704 678 132 783 902 760 689 765>