您的位置:首页 > 其它

一个女人生小孩的概率 问题

2007-07-11 08:45 260 查看



/**//*一个女人生小孩的概率 问题


总共生四个小孩


a 都是 男的 或都是女的


b 两个男的 和两个女的


c 三个男的和一个女的 或三个女的和一个男的


求a b c 的概率


只用到 if 和 for语句


和Math.random这个函数!~ */




import java.text.DecimalFormat;






public class Probability ...{




public int totalCount = 100000;// 总循环次数




DecimalFormat myFormat = new DecimalFormat("#0.0000");




// 都是 男的 或都是女的




public void viewA() ...{


int okCount = 0;




for (int i = 0; i < totalCount; i++) ...{


int temp = 0;


for (int j = 0; j < 4; j++)


temp += (int) (Math.random() * 10 + 1);


if (temp == 40 || temp == 4)


okCount++;


}


double d = (1.0 * okCount / totalCount + 0.0000005) * 1000;


//System.out.println(d + " " + okCount);


System.out.println(myFormat.format(d) + "/" + (totalCount * 1000));


}




// 两个男的 和两个女的




public void viewB() ...{


int okCount = 0;




for (int i = 0; i < totalCount; i++) ...{


int man = 0, woman = 0;




int[] temp = ...{ (int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1) };




for (int j = 0; j < 4; j++) ...{


if (temp[j] == 10)


man++;


else if (temp[j] == 1)


woman++;


else


continue;


}


if (man == 2 && woman == 2)


okCount++;


}


double d = (1.0 * okCount / totalCount + 0.0000005) * 1000;


System.out.println(myFormat.format(d) + "/" + (totalCount * 1000));


}




// 三个男的和一个女的 或三个女的和一个男的




public void viewC() ...{


int okCount = 0;




for (int i = 0; i < totalCount; i++) ...{


int man = 0, woman = 0;




int[] temp = ...{ (int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1),


(int) (Math.random() * 10 + 1) };




for (int j = 0; j < 4; j++) ...{


if (temp[j] == 10)


man++;


else if (temp[j] == 1)


woman++;


else


continue;


}


if ((man == 3 && woman == 1) || (man == 1 && woman == 3))


okCount++;


}


double d = (1.0 * okCount / totalCount + 0.0000005) * 1000;


System.out.println(myFormat.format(d) + "/" + (totalCount * 1000));


}






public static void main(String[] args) ...{


Probability p = new Probability();


p.viewA();


p.viewB();


p.viewC();


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: