【问题标题】:Modulo if statement not producing expected output模if语句没有产生预期的输出
【发布时间】:2017-10-30 16:05:41
【问题描述】:

我编写了一个数学问题提示器。并想确保在分裂的情况下。结果只是整数,不被0除。使用以下代码。

while tries < problems:
    print("What is ....")
    print()
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    operation = random.randint(1,4)
    if operation == 1:
        op = '-'
    if operation == 2:
        op = '+'
    if operation == 3:
        op = '/'
        while num2 == 0 or num1%num2 > 0:

               num1 = random.randint(0,9)
               num2 = random.randint(0,9)

但是。产生的唯一问题是答案总是 1. 0. 或分子。 仅举例: 4/1 5/1 6/1 或者 0/5 0/6 0/6 或者 3/3 2/2 1/1

【问题讨论】:

  • 嗯,您的代码按预期工作。确实,由于在这么小的间隔内生成数字的性质,您提到的情况会更频繁地出现,但是除非您增加随机整数生成器的间隔大小,否则您无法绕过它。

标签: python if-statement random while-loop modulo


【解决方案1】:

您的代码看起来不错(除了最后两行的缩进之外,但我认为它在复制代码时已更改)。

我用固定种子在 python fiddle 中运行它以获得可重现的结果:

import random

random.seed(21334261)
print("What is ....")
print()
num1 = random.randint(0,9)
num2 = random.randint(0,9)
print("num1: {} \n num2: {}".format(num1, num2))
operation = 3
if operation == 1:
    op = '-'
if operation == 2:
    op = '+'
if operation == 3:
    op = '/'
    while num2 == 0 or num1%num2 > 0:  
        num1 = random.randint(0,9)
        num2 = random.randint(0,9)

print("num1: {} \n num2: {}".format(num1, num2))

我得到输出 8 和 4。

我的猜测是这只是概率问题:如果 num2=1 或 num1=0,您的条件将始终为真。

另一方面,只有少数其他案例有效且不属于您描述的类别:9/3 8/4 8/2 6/3 6/2 4/2。

编辑:更正了 while 块的缩进,感谢 MaximTitarenko。

【讨论】:

  • 最后一个while 块的缩进是正确的,因为它从问题中得出:in the case of division. the outcome is only whole numbers and not being divided by 0,OP 只想为operation == 3 划分实现它
  • 啊,我明白了,这很有道理!谢谢指正。
【解决方案2】:

好的,所以我不是 100% 同意这一点,但我的结果确实显示了几个实际问题的实例,例如 3、6、7、9,但像你描述的那样更有可能发生,并且当你也用随机操作运行它时,你得到相当罕见的真正除法问题的机会就会大大降低

1 num1 0 num2 4
2 num1 3 num2 3
3 num1 6 num2 3
4 num1 4 num2 4
5 num1 4 num2 4
6 num1 6 num2 2
7 num1 8 num2 2
8 num1 5 num2 1
9 num1 8 num2 2
10 num1 6 num2 1
11 num1 0 num2 6
12 num1 3 num2 3
13 num1 5 num2 5
14 num1 6 num2 2
15 num1 4 num2 1
16 num1 9 num2 1
17 num1 0 num2 5
18 num1 0 num2 8
19 num1 0 num2 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多