出现逻辑错误时,将打印出三个或五个整数的所有数字之和

时间:2018-06-25 13:01:46

标签: python python-3.x logic

我的程序出现一些逻辑错误。在过去的几个小时中,我一直在尝试解决此问题。应该打印出三个或五个整数倍的所有数字的总和。

我的输出

1.)enter an integer number (0 to end): enter an integer number (0 to end):
2.)enter an integer number (0 to end): 3+ = 3

预期产量

1.)enter an integer number (0 to end): 3 = 3
2.)enter an integer number (0 to end): 3+5 = 8

下面是我的代码。

while True:
  answer = ""
  num = int(input("enter an integer number (0 to end): "))
  end_answer = 0

  if num == 0:
    exit()

  for i in range(1, num+1):
    if i%3==0 or i%5==0 :
      answer += str(i)
      end_answer += i


    if i != num and (i%3==0 or i%5==0):
      answer += "+"
      print(str(answer) + " = " + str(end_answer) )

我没有在python中看到类似的答案

2 个答案:

答案 0 :(得分:2)

以下(适当缩进)代码将为您提供所需的内容:

while True:
    num = int(input('Enter an integer number (0 to end): '))
    if num == 0: exit()

    answer = ''
    end_answer = 0
    sep = ''
    for i in range(1, num+1):
        if i % 3 == 0 or i % 5 == 0 :
            answer += sep + str(i)
            sep = ' + '
            end_answer += i

    if end_answer > 0:
        print(str(answer) + ' = ' + str(end_answer) )

请注意,它使用变量分隔符sep来更清晰地打印出您要计算的项目。运行示例如下:

Enter an integer number (0 to end): 2
Enter an integer number (0 to end): 3
3 = 3
Enter an integer number (0 to end): 10
3 + 5 + 6 + 9 + 10 = 33
Enter an integer number (0 to end): 38
3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20 + 21 + 24 + 25 + 27 + 30 + 33 + 35 + 36 = 329
Enter an integer number (0 to end): 0

答案 1 :(得分:1)

通过使用内置的sum f-strings 用于打印文本格式,可以大大简化代码。这也可能会更有效。

代码

from itertools import count

counter = count(1)

while True:
    num = int(input(f'{next(counter)}). Enter an integer number (0 to end): '))

    if num == 0:
        break

    nums = [x for x in range(1, num + 1) if x % 3 == 0 or x % 5 == 0]
    print(f'{" + ".join(map(str, nums))} = {sum(nums)}')

输出

1). Enter an integer number (0 to end): 3
3 = 3
2). Enter an integer number (0 to end): 9
3 + 5 + 6 + 9 = 23
3). Enter an integer number (0 to end): 15
3 + 5 + 6 + 9 + 10 + 12 + 15 = 60
4). Enter an integer number (0 to end): 0