c言語のランダム生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <stdlib.h> #include <time.h> void init(){ srand(time(NULL)); } double getRandomDouble(){ return rand() * 1.0 / RAND_MAX; } int getRandomInt(int min, int max){ if(max < min){ return max; } double d = getRandomDouble(); int randomOffset = (int)(d * (max - min + 1)); return min + randomOffset; } int main(){ init(); int n; int intMin = -3; int intMax = 7; int times = 10000; int min = 0; int max = 0; for(int i=0; i<times; i++){ n = getRandomInt(intMin, intMax); if(n < min){ min = n; } if(max < n){ max = n; } } printf("max = %d\n", max); printf("min = %d\n", min); } |
1 2 |
max = 7 min = -3 |
yuzunoha, thanks so much for the post.Really thank you! Great.