見出し画像

C言語 乱数の発生

乱数関連の関数

------------------------------------------------------------------------

srand()関数    (stdlib.hのインクルードが必要)

randで発生させる乱数の系列を変更。

rand()関数    (stdlib.hのインクルードが必要)

0~RAND_MAX(処理系依存)の間の疑似乱数を返す。

(RAND_MAXの確認)

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

int main(void) {
    printf("RAND_MAX=%d\n", RAND_MAX);
    return 0;
}
RAND_MAX=32767

time()関数    (time.hのインクルードが必要)

1970年1月1日00:00:00~現在までの経過時間を秒単位で取得する。

--------------------------------------------------------------------------

例1)0~99の乱数を100個発生させてみる

コード

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

int main(void){
    int i,j;
    // 乱数系列の変更 
    srand((unsigned) time(NULL));
    //0~99の擬似乱数を100個発生
    for (i=1; i<=10; i++) {
        for (j=0; j<10; j++) {
            printf("%2d ",rand()%100);
        }
        printf("\n");
    }
    return 0;
}

実行結果(ランダムですが1例)

 0 99 62 29  4 81 39 85 51 44
45  7 91 14 23 83 13 36 36 15
45 83 81 17 69 65 42 93 48 18
48  3 44 71 82 98  1 72 16 34
96 17  3  8 69 95 58 35 44 24
84 92 66 61 67 81 50 26 40 15
93 27 76 15 44 73 87 94 19 62
51 87 27  9 40 89 76 98 37 28
87 66 29 61 27 73 43 81 96 63
94 49 57 17 45 40 87 64 31 89

例2)乱数を用いて長方形を計算する。

コード


#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void){ int a,b; //乱数系列の変更 srand((unsigned) time(NULL)); //1から10までの乱数を発生させる a = rand() % 10 + 1; b = rand() % 10 + 1; //計算結果を出力 printf("%d * %d = %d¥n",a,b,a*b); return 0; }

実行結果(ランダムですが1例)

3 * 4 = 12

--------------------------------------------------------------------------------

もう少し詳しく勉強したら追記するかも。


以上

2019/08/16 AM 2:25