代码如下:
#include "stdio.h" #include "stdlib.h" #include "time.h" #include "windows.h" int unbalancedcoin(){ int a = rand() % 10; if (a > 6)return 0; else return 1; } int banlancedcoin(){ SYSTEMTIME currentTime; GetSystemTime(¤tTime); srand(currentTime.wMilliseconds); int a = unbalancedcoin(); int b = unbalancedcoin(); while (a == b){ b = unbalancedcoin(); } return b; } int rand6(){ int a = ~(1 << 31); while (a > 6){ a = 4 * banlancedcoin() + 2 * banlancedcoin() + banlancedcoin() - 6; } return a; } void main(){ int sum[6] = { 0 }; int tmp; int a[10000]; /*for (int i = 0; i < 10000; i++){ tmp = rand6(); a[i] = tmp; sum[tmp - 1]++; } for (int i = 0; i < 10000; i++){ printf("%d\t", a[i]); } printf("***********\n"); for (int i = 0; i < 6; i++){ printf("%d\t", sum[i]); }*/ for (int i = 0; i < 10000; i++){ tmp = banlancedcoin(); a[i] = tmp; sum[tmp]++; } for (int i = 0; i < 10000; i++){ printf("%d\t", a[i]); } printf("***********\n"); for (int i = 0; i < 2; i++){ printf("%d\t", sum[i]); } getchar(); }
运行10次,每次都是7:3 或者6:4 ,,反正前面的比例总要稍大点,
你用的>6, rand()%10, 分别是0~9
>6, 得到的要求是7 8 9 三个数字, 当然是7:3左右
-----
加我微信214710841, 可以一起交流哦