You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

While循环条件设置及子女数量频率统计问题排查求助

模拟“生育至儿女双全”程序的问题排查与修复

编写模拟“生育子女直到同时拥有至少一个男孩和一个女孩”的程序时,先后遇到了这些问题:

  • 初始阶段While循环无法正常执行,所有频率统计结果全为0
  • 修复循环问题后,无法确定正确的循环终止条件,以实现“直到儿女双全才停止”的逻辑
  • 调整循环条件后,又出现了列表索引越界的错误,最终在他人协助下完成了修复

修复后的代码

import sys
import random
import stdarray

n = int(sys.argv[1])

boy = 0
girl = 1
frequencies = stdarray.create1D(6, 0)

for i in range(n):
    boys = 0
    girls = 0
    while boys < 1 or girls < 1:
         child = random.randint(0, 2)
         if child == boy:
             boys += 1
         elif child == girl:
             girls += 1
    children = boys + girls
    if children >= 5:
         frequencies[5] += 1
    else:
         frequencies[children] += 1
    boys = 0
    girls = 0

(注:运行代码需确保已导入sys、random和stdarray模块)

预期命令行输出示例

python boysandgirls.py 1000  
Avg # children: 3  
Trials with 2 children: 490  
Trials with 3 children: 260  
Trials with 4 children: 143  
Trials with 5 or more children: 107  

python boysandgirls.py 1000  
Avg # children: 3 Trials with 2 children: 509  
Trials with 3 children: 245  
Trials with 4 children: 119  
Trials with 5 or more children: 127  

内容的提问来源于stack exchange,提问作者Abby Kabalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:45:46