首页 > 解决方案 > 如何计算从开始到的整数个数

问题描述

编写一个函数 div_3_5(start, end) 计算从 start 到的整数个数,但不包括使用 while 循环可被 3 或 5 整除的 end。

注意:我必须在这个练习的函数中使用 while 循环(我知道 for 循环是最好的)。

示例: div_3_5(7, 27) 计算结果为 9(在该范围内可被 3 或 5 整除的数字:9,10,12,15,18,20,21,24,25)

我真的不明白为什么或我在做什么,有人可以解释我哪里出错了。到目前为止,这是我的代码:

count = 0
def div_3_5(start, end):
    while start < end:
        if start%3 == 0 or start%5 == 0:
            count + 1
        start = start + 1
            start + 1
    return count

这显然不完整或不正确,我得到的当前错误是:

预期输出:

div_3_5(7, 27) -> 9

测试结果:0 != 9

标签: pythonwhile-loop

解决方案


我找到的答案是:

def div_3_5(start, end):
count = 0
while start < end:
    if start % 3 == int() or start % 5 == int():
        count += 1
    start = start + 1
return count

推荐阅读