【问题标题】:Why am I not receiving output for this while loop in python?为什么我在 python 中没有收到这个 while 循环的输出?
【发布时间】:2019-07-07 11:57:05
【问题描述】:

我是 python 新手,正在尝试通过小项目学习:

我正在尝试编写一个代码,如果假设您和其他 n 个学生在一个大型讲座班上。确定 n 必须有多大,以使某人与您生日相同的概率大于 50%? 注意:忘记闰年 所以假设一年有 365 天,没有人和你生日相同的概率是 (364/365)**n

我的代码是:

n=probability
probability = 0
while n==0.50*n:
    print("With n students, the
probability
is greater than
50% that someone has the same
birthday
as you.")

我哪里出错了?如何实现 if 语句?我正在寻找的输出是:

有 253 名学生,某人的概率大于 50% 和你同日生日。

【问题讨论】:

  • 1.浮点数几乎永远不会完全等于其他浮点数,使用== 几乎永远不会成功。 2. 哪个n 正好等于n*0.5...?
  • n 有什么变化?
  • 我建议在尝试编码之前用简单的古英语编写一个算法。
  • 没有值永远等于自身的一半。
  • ...好吧,我猜是零和无穷大。 :-)

标签: python function if-statement while-loop


【解决方案1】:

如果不完全重做,我不知道如何修复您的代码,所以我们开始吧:

p = 1/365
n = 0

# Search for the number of students that ensures p(same birthday)>50%.
while 1-(1-p)**n < 0.50 :
    n = n+1

print("With {number} students, the probability is greater than 50% that someone has the same birthday as you.".format(number=n))

请随时询问更多信息。

【讨论】:

  • 谢谢你的作品。但是你能解释一下你在 print 下写的 {number} 字典吗?我对它不是很熟悉。它是如何检测到 253
  • 在while 循环的末尾,我们有 n=253。现在您可以通过多种方式格式化字符串。在"With {number} students".format(number=n) 中使用.format,我们告诉字符串用n 替换括号之间的变量。或者,如果您愿意,您可以使用"With %d students" %n。这是格式化字符串的有用链接:pyformat.info
【解决方案2】:

这没有返回输出,因为 n==0.5*n 的条件为假,因此循环从不开始运行。

【讨论】:

  • 这个脚本无论如何都会在第一行n = probability引发一个NameError。
猜你喜欢
  • 2020-01-17
  • 2022-06-17
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
相关资源
最近更新 更多