C语言模拟生男生女问题


C语言模拟生男生女概率问题

cover pid:79967420

题目:在一个重男轻女的国家里,每家每户都想生男孩。若一户人家生了一个女孩,便会在生一个,直到生下的是男孩为止。问这个国家的男女比例是否还是1:1?

这是一道稍微有些违背直觉的题目,答案是,然而在我进行的投票中有53%的人选择了不是,也就是说超过一半的人都选错了。

我们用C语言模拟一下这个问题:由于生孩子的性别是不确定的,我们肯定要用到随机数。C语言在<stdlib.h>库中提供了rand()srand()函数来生成随机数。rand()srand()<time.h>中的time()一般搭配使用。

我们假设有十万对夫妇,每次生孩子都生成一个随机数,用这个随机数对2取余,结果为0表示男孩,结果为1表示女孩。最后计算男女比例。考虑设置一个for循环表示十万对夫妇生孩子的过程,随机数出来之后过一个while循环判断性别,过了男孩的数量就+1,没过就让女孩的数量+1,再生成随机数继续判断性别,知道生出男孩为止。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
    srand((unsigned)time(NULL));
    int cnt_boy=0;
    int cnt_girl=0;
    for(int i=0;i<100000;i++){
        int sex=rand()%2;
        //printf("%d\n",sex);
        //假设sex=0表示男孩,sex=1表示女孩
        while(sex!=0){
            sex=rand()%2;
            cnt_girl++;

        }
        cnt_boy++;

    }
    printf("the number of boy is %d\n",cnt_boy);
    printf("the number of girl is %d\n",cnt_girl);
    float rate=(float)cnt_boy/(float)cnt_girl;
    printf("the rate of boy/girl is %f",rate);
    return 0;
}

程序跑三次的结果为:

the number of boy is 100000
the number of girl is 99866
the rate of boy/girl is 1.001342

the number of boy is 100000
the number of girl is 100478
the rate of boy/girl is 0.995243

the number of boy is 100000
the number of girl is 100123
the rate of boy/girl is 0.998771

误差只在小数点后三位,可以近似得到男女比例为1:1。

事实上,自然出生的性别比例、也就是所谓第二性别比是104:100,影响性别比例的原因主要有对于女性胚胎的堕胎以及对于女婴的弃婴,杀婴等现象。


文章作者: eacryo
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 eacryo !
  目录