首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

C 随机数,获取min至max其间的随机数(尽可能公平)

2013-09-10 
C 随机数,获取min至max之间的随机数(尽可能公平)#include unistd.h#include stdlib.h#include time.h

C 随机数,获取min至max之间的随机数(尽可能公平)

#include <unistd.h>#include <stdlib.h>#include <time.h>#include <math.h>#include <stdio.h>static int getRand(int min, int max);int count=20;int main(int argc, char **argv){int i;int rd;int h_ct=0;    int min_ct1 = 0;int z_ct=0;    int max_ct1 = 0;    int max_ct = 0;    int min=atoi(argv[1]);    int max=atoi(argv[2]);    int min1=min+1;    int max1=max-1;    if(argc>3) count = atoi(argv[3]);    printf("min=%d, max=%d\n", min, max);for(i=0;i<count;i++){rd =  getRand(min,max);if(rd==max)      h_ct++;else if(rd==min)  z_ct++;else if(rd==min1) min_ct1++;else if(rd==max1) max_ct1++;else if(rd>max) max_ct++;}printf("Times of : min=%d, min+1=%d, max-1=%d, max=%d, big than max=%d\n",z_ct, min_ct1, max_ct1, h_ct, max_ct);return 0;}static int srand_seed_set = 0; //#define RD_PIECE 1/RAND_MAX;static int getRand(int min, int max){if(!srand_seed_set){srand_seed_set = 1;time_t t;srand((unsigned) time(&t));}    if(max < min) return min;    double m = 1.0/(max-min+1);double d = ((double)rand())/RAND_MAX;return min+d/m;}


效果:

[zty@lein ~]$ gcc -o t1 t1.c -lm && ./t1 21 112 2000000min=21, max=112Times of : min=22005, min+1=21698, max-1=21651, max=21758, big than max=0[zty@lein ~]$ ./t1 1 100 20000000                                                                                                                                    min=1, max=100Times of : min=200198, min+1=199927, max-1=200231, max=200204, big than max=0[zty@lein ~]$ ./t1 11 133 20000000                                                                                                                                              min=11, max=133Times of : min=162382, min+1=162602, max-1=162525, max=162750, big than max=0


 

 

 

热点排行