Suppose rand5 can generate 1 ~ randomly ~ Use rand5 to generate rand7 () 1 ~ 7 (Equal Probability)
1. use rand5 to obtain rand2 (). When the number generated by rand5 is greater than 2, It loops until it generates 1 or 2 and the probability of generating 1 and 2 is 1/2, because the probability of generating 1 and generating 2 is equal.
2. use rand2 to generate 0 and 1 (minus 1), and use it three times in a row. There are 8 possibilities (in binary format): 000 001 010 011 100 101 110, when the number of generated values is 000, re-calculate the number. In this way, we can get 1 ~ The number in the range of 7, and the probability is equal.
# Include <iostream> # include <math. h> using namespace STD; int rand5 () {return rand () % 5 + 1;} int rand2 () {int temp; do {temp = rand5 ();} while (temp> 2); Return temp;} int rand7 () {int temp; do {temp = (rand2 ()-1) <2; temp + = (rand2 ()-1) <1; temp + = rand2 ()-1;} while (temp = 0); Return temp ;} int main (INT, char **) {int num; cout <"Total number of inputs:"; CIN> num; int C1, C2, C3, C4, C5, c6, C7; C1 = C2 = C3 = C4 = C5 = C6 = C7 = 0; For (INT I = 0; I <num; I ++) {int temp = rand7 (); Switch (temp) {Case 1: C1 ++; break; Case 2: C2 ++; break; Case 3: C3 ++; break; case 4: C4 ++; break; Case 5: C5 ++; break; Case 6: C6 ++; break; Case 7: C7 ++ ;} // cout <temp <"\ t" ;}cout <Endl; cout <"the number of generated 1 accounts for the total number of generated:" <(double) c1/num * 100 <"%" <Endl; cout <"the number of generated 2 accounts for the total number of generated:" <(double) c2/num * 100 <"%" <Endl; cout <"the number of generated 3 accounts for the total number of generated:" <(double) c3/num * 100 <"%" <Endl; cout <"the number of generated 4 accounts for the total number of generated:" <(double) c4/num * 100 <"%" <Endl; cout <"the number of generated 5 accounts for the total number of generated:" <(double) c5/num * 100 <"%" <Endl; cout <"the number of generated 6 accounts for the total number of generated:" <(double) c6/num * 100 <"%" <Endl; cout <"the number of generated 7 accounts for the total number of generated:" <(double) c7/num * 100 <"%" <Endl; return 0 ;}