int random_01() {//等概率返回0,1;
return rand() % 2;
}
int random_ab(int a, int b) {//等概率返回区间[a,b]的整数;
int m = b - a;
int n = 1;
for (;pow(2, n) - 1 < m;n++);//获取表示M所需的位数;
int res;
do {
res = 0;//每次循环开始将res置零;
for (int i = 0;i < n;i++) {
res += random_01()*pow(2, i);
}
} while (res>m);//不断循环,直到得到res的值小于等于m;
return res + a;
}
void test_of_random_ab() {//测试random_ab;
int m = 0;
int a[5] = { 0 };
for (int i = 0, k = 0;i < 100;i++) {//统计4,5,6,7,8出现的次数;
k = random_ab(4, 8);//函数的调用;
if (k == 4)
a[k - 4]++;
else if (k == 5)
a[k - 4]++;
else if (k == 6)
a[k - 4]++;
else if (k == 7)
a[k - 4]++;
else if (k == 8)
a[k - 4]++;
m += k;
}
for (int i = 0;i < 5;i++) //输出4,5,6,7,8出现的次数;
cout << i + 4 << ends << a[i] << endl;
cout << "Exception:" << m / 100.0 << endl;//求取产生的均值;
}