乱数の生成 <C言語>

time()でtime_t型の整数値を取得します。

<書式>
#include<time.h>              
time_t time(time_t *timer);

time_t timer;
time(&timer);

time_t型の整数値を符号なし整数型にキャストして乱数系列を初期化するseed値とします。

unsigned int seed;
seed = (unsigned int) timer;

srand()で乱数系列を初期化します。

<書式>
#include <stdlib .h>               
void srand (unsigned int seed);

srand(seed);

rand()で0からRAND_MAXの範囲内の擬似乱数を生成します。

<書式>
#include <stdlib .h>
int rand (void);

printf("%d\n", rand());

サンプルコード

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

int main(void){

        time_t timer;
        time(&timer);

        unsigned int seed;
        seed = (unsigned int) timer;

        srand(seed);

        int i;

        printf("0~%dまでの乱数\n", RAND_MAX);
        for(i = 0; i < 3; i++){
                printf("%d\n", rand());
        }

        printf("1~100までの乱数\n");
        for(i = 0; i < 3; i++){
                printf("%d\n", rand() % 100 + 1);
        }

        return 0;
}

実行結果





コメント

このブログの人気の投稿

Tomcatの環境構築

レトロパソコン(NEC PC-8001)が正常起動

レトロパソコン(NEC PC-8001)を動かしたいなあ