说澳大利亚的父母喜欢女孩,如果生出来的第一个女孩,就不再生了,如果是男孩就继续生,直到生到第一个女孩为止,问若干年后,男女的比例是多少?
用程序验证基本上是1:1
- #include <stdio.h>
- #include <stdlib.h>
- #define MAN 1 //男孩
- #define WOMAN 0 //女孩
- static int g_iManNum = 0; //男孩个数
- static int g_iWoManNum = 0; //女孩个数
- static void AddOneMan()
- {
- g_iManNum++;
- }
- static void AddOneWoman()
- {
- g_iWoManNum++;
- }
- static int GetOneChild()
- {
- return (rand()%2);
- }
- static void PrintResult()
- {
- printf("Man's number is %d, woman's number is %d./n", g_iManNum,
- g_iWoManNum);
- float fResult = (float)g_iManNum / (float)g_iWoManNum;
- printf("Man / Woman is [%f]/n", fResult);
- }
- static void OneFamilyGetChild()
- {
- int iChildType = GetOneChild();
- if (MAN == iChildType)
- {
- //如果是男孩,则递归调用,再生一个小孩,直到生出一个女孩为止
- AddOneMan();
- OneFamilyGetChild();
- }
- else if (WOMAN == iChildType)
- {
- AddOneWoman();
- }
- else
- {
- printf("child type is error!/n");
- exit(0);
- }
- }
- static void StatisticsOfAllFamily(int iFamilyCount)
- {
- printf("Now family count is %d./n", iFamilyCount);
- int i = 0;
- for (i = 0; i < iFamilyCount; i++)
- {
- OneFamilyGetChild();
- }
- PrintResult();
- }
- int main ()
- {
- srand(time(NULL));
- StatisticsOfAllFamily(1000000);
- return 1;
- }
最终的结果是0.9996约等于1,男孩小于女孩。我运行了多次,都是这个结果。从理论上来说,不一定”男孩个数一定小于女孩个数“,但是结果每次都是这样,可能是“男孩个数小于女孩个数”出现的几率比较高。