zoukankan      html  css  js  c++  java
  • 一道概率题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 }

     --

  • 相关阅读:
    如何:为 Silverlight 客户端生成双工服务
    Microsoft Sync Framework 2.1 软件开发包 (SDK)
    Windows 下的安装phpMoAdmin
    asp.net安全检测工具 Padding Oracle 检测
    HTTP Basic Authentication for RESTFul Service
    Windows系统性能分析
    Windows Server AppFabric Management Pack for Operations Manager 2007
    Mongo Database 性能优化
    服务器未能识别 HTTP 标头 SOAPAction 的值
    TCP WAIT状态及其对繁忙的服务器的影响
  • 原文地址:https://www.cnblogs.com/graphics/p/1683959.html
Copyright © 2011-2022 走看看