首页 > 解决方案 > 为什么我得到重复的答案?

问题描述

我只是在学习 python 并且已经开始使用 if / while 语句,这个基本程序旨在确定是否可以仅使用现有的行将一块巧克力分成 x 块。

它在 99% 的时间内都有效,但偶尔我会得到 YES YES 的结果。下面的例子。(useless 只是我用来结束没有 else 的 IF 语句的占位符。)

length = int(6)
chunks = int(6)
total = row*length
row_a = total
length_a = total
useless = 0
no = 0
if chunks == total:
    print("YES")
else:
    useless = useless +1
while row_a != 0:
    if chunks == total - row_a:
        print("YES")
        break
    else:
        row_a = row_a - row
        if row_a == 0:
            no = no+1
        else:
            useless = useless +1
while length_a != 0:
    if chunks == total - length_a:
        print("YES")
        break
    else:
        length_a = length_a - length
        if length_a == 0:
            no = no +1
        else: useless = useless +1
else: useless = useless +1
if no == 2:
    print("NO")
else: useless = useless +1 ```

标签: pythonwhile-loop

解决方案


我建议您从头开始检查问题,并在开始编码之前尝试解决它。您的代码对于一个简单的问题来说太复杂了。

这是可以解决问题的代码示例。

x, y = 8, 10 #length and width of the chocolate bar

p_s = 5 #pieces size
p_n = int(input('Number of pieces: '))

total=x*y #size of the chocolate bar

if total//p_s < p_n:
    print('NO')
else:
    print('YES')

推荐阅读