主题:【讨论】【跟进】趣味数学题 (三) -- 数值分析
共:💬53 🌺38
是Java写的,写得急了点,将就看吧:
package com.mycompany.app; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Hello CCHere! * */ class Stat { public boolean k1; public boolean k2; }; public class App { //true is a boy, false is a girl //true if k1 is selected, false if k2 is selected for the first meeting public static boolean getRandomTrueOrFalse() { Random random = new Random(); return random.nextBoolean(); } public static void main( String[] args ) { boolean k1; boolean k2; float anotherKidIsBoyCount; List<Stat> ls = new ArrayList<Stat>(); for (int i=0; i<10000; i++) { k1 = getRandomTrueOrFalse(); k2 = getRandomTrueOrFalse(); if (k1 || k2 ) { //if one of the kid is a boy, add they to the statistic list. The two girl scenario can be removed Stat st = new Stat(); st.k1 = k1; st.k2 = k2; ls.add(st); } } anotherKidIsBoyCount=0; for (Stat st : ls) { if (st.k1) { //if first kid is selected and first kid is a boy if (st.k2) {// if second kid is a boy, increase the counter anotherKidIsBoyCount++; } } else { if (st.k2) { // if 2nd kid is selected , and second it is a boy if (st.k1) { //if first kid is a boy, increase the counter anotherKidIsBoyCount++; } } } } System.out.println("cchere math question answer: " + String.valueOf( anotherKidIsBoyCount/ls.size())); } }
输出是:
cchere math question answer: 0.33188406
作者 对本帖的 补充(1)
if (st.k1) { //if first kid is selected and first kid is a boy if (st.k2) {// if second kid is a boy, increase the counter anotherKidIsBoyCount++; } } else { if (st.k2) { // if 2nd kid is selected , and second it is a boy if (st.k1) { //if first kid is a boy, increase the counter anotherKidIsBoyCount++; } } }
这段代码有其实可以简化为
if (st.k1 && st.k2) { anotherKidIsBoyCount++; }
我写得那么麻烦,存粹就是为了模拟见到第一个,检查第另一个孩子的场景。
- 相关回复 上下关系8
🙂为什么不是一儿一女和两个儿子的可能各占一半呢? zero9999 字727 2021-05-07 06:33:52
🙂你的模拟不够逼真 懒厨 字732 2021-05-07 07:58:44
🙂不如写代码还看得清楚点 zero9999 字0 2021-05-07 08:01:49
😄代码来了
🙂这个趣味数学题 (三)大概是你对了 1 zero9999 字667 2021-05-07 23:11:16
😄我大学毕业后就没写过C了 1 懒厨 字380 2021-05-08 02:18:26
🙂你的代码好像有问题 3 孟词宗 字1259 2021-05-07 16:35:12
🙂我现在同意你的观点 唐家山 字24 2021-05-08 04:16:13