time.h
time(NULL) で1970年1月1日0時0分0秒(UTC)からの経過秒数を取得できる。
型は time_t。
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t;
t = time(NULL);
// 1970年1月1日0時0分0秒(UTC)からの経過秒数
printf("%ld\n", t);
}
乱数を作るシードへ整数値を与えるために使う。
stdlib.h
一般的なユーティリティライブラリ。
乱数のシードを作るsrand 、乱数を作るrand を含んでいる。
rand(void) は、0からRAND_MAX の間の疑似乱数を返す。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a, b;
//randが返す乱数はsrandで初期化される。
//srandを呼び出さずにrandを使った場合は、srand(1)と同じ。
a = rand();
b = rand();
printf("%d, %d\n", a, b);
// 上と同じ結果。
srand(1);
a = rand();
b = rand();
printf("%d, %d\n", a, b);
// 上と異なる結果。
srand(777);
a = rand();
b = rand();
printf("%d, %d\n", a, b);
return 0;
}
乱数列
time(NULL) で取得した整数値をsrandの引数にして乱数列を作る。
決まり文句。
srand((unsigned)time(NULL));
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int a, b;
time_t t;
t = time(NULL);
srand((unsigned)t);
a = rand();
b = rand();
printf("a is %d, b is %d.\n", a, b);
// time(NULL) の取得結果が変わるまで大体一秒ぐらい待つ。
while (1) {
if (t != time(NULL)) {
break;
}
}
//上とは異なる乱数が取得される。
srand((unsigned)time(NULL));
a = rand();
b = rand();
printf("a is %d, b is %d.\n", a, b);
return 0;
}
0から9の乱数を取得する決まり文句。
(int)((rand() / ((double) RAND_MAX + 1.0)) * 10)
ある範囲の整数からなる乱数はどうやったら生成することができるか。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int a, b;
srand((unsigned)time(NULL));
// [0, 9] の乱数を発生。
a = (int)((rand() / ((double) RAND_MAX + 1.0)) * 10);
b = (int)((rand() / ((double) RAND_MAX + 1.0)) * 10);
printf("a is %d, b is %d.\n", a, b);
return 0;
}