五千年(敝帚自珍)

主题:【讨论】【跟进】趣味数学题 (三) -- 数值分析

共:💬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++;
 }

我写得那么麻烦,存粹就是为了模拟见到第一个,检查第另一个孩子的场景。

全看分页树展 · 主题 跟帖


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河