一道概率题From VCK 小白

题目描述:一个随机函数f(),只返回1和0,返回1的概率是p,返回0的概率是1-p,构造另外一个函数,只返回1和0,概率各1/2

答案,有代码有真相

 1 int func()
 2 {
 3     int i ;
 4     int j ;
 5     while(true
 6     {
 7         i = f() ;
 8         j = f() ;
 9         if(i == 1 && j == 0)
10             return 1;
11         else if(i == 0 && j == 1)
12             return 0;
13     }
14 }

以下代码等概率产生0和1

代码
 1 #include <iostream>
 2 #include "time.h"
 3 using namespace std ;
 4 
 5 
 6 int main(void)
 7 {
 8     srand((unsigned int)time(0));
 9 
10     int c0 = 0 ;    // count for 0
11     int c1 = 0 ;    // count for 1
12 
13     // 随机产生1000次,i越大,c0和c1就越接近1:1
14     for (int i = 0; i < 1000++i)
15     {
16         int m = rand() % 2;
17         int n = rand() % 2 ;
18 
19         // 构造两个等概率事件
20         // 以下两个if语句对应两个等概率事件,所以当i足够大的时候,c0和c1应该是趋于相等的
21         if (m == 0 && n == 1)
22         {
23             cout << 0 ;
24             ++c0 ;
25         }
26 
27         if (m == 1 && n == 0)
28         {
29             cout << 1 ;
30             ++c1 ;
31         }
32     }
33     
34     cout << "number of 0 is: " << c0 << endl ;
35     cout << "number of 1 is: " << c1 << endl ;
36 
37     system("pause") ;
38     return 0 ;
39 }

 --

原文地址:https://www.cnblogs.com/graphics/p/1683959.html