Using random number generator to generate a number with a given expected value
问题 I came across the following question: Using rand() function, generate a number with expected value k. Options are: 1) int GetRandom(int k) { v=0; while(rand()<1.0f/(float)k) v++; return v; } 2) int GetRandom(int k) { v=0; while(rand()<(1-1.0f/(float)k)) v++; return v; } 3) int GetRandom(int k) { v=0; while(rand() > (1-1.0f/(float)(k+1))) v++; return v; } 1) seemed like the correct answer. Examining the outcome for specific values of k seems to indicate this is the not the case. (I set k=3 .