C言語のrandom関数の使い方は?
C言語のrand()関数は擬似乱数を生成するために用いられます。rand()関数を使用する基本的な例は以下の通りです。
- ヘッダーファイルをインクルード:
#include <stdlib.h>
#include <time.h>
これらの2つのヘッダファイルはそれぞれrand()関数と種関数srand()を含みます。
- srand();
srand(time(0));
- rand()
- RAND_MAX
int randomNumber = rand();
サンプルコードそのもの:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 设置种子
srand(time(0));
// 生成随机数
int randomNumber = rand();
printf("随机数:%d\n", randomNumber);
return 0;
}
rand() 함수는 유사난수를 생성하는데, 동일한 시드에서의 결과는 동일하다. 더 나은 난수성을 얻으려면 다른 난수 알고리즘을 병합해 난수를 생성할 수 있다.