python - 在 python 中使用 while 循环将所有可被 y 整除的数字 0 到 x 求和

标签 python while-loop

我需要使用 while 循环(不使用任何 for 函数)编写脚本来对 0 和 x 之间可被 div1 整除的所有数字求和。 这就是我的。

def sum_upto_divisible(x,div1):
    i=0
    while i<x:
        i+=1
        if i%div1==0:
            i+=i
    return(i)

如果 x = 25 和 div1=5,答案应该是 50。我当前的循环给出的答案是 30。我知道循环是加到 5,然后加倍。然后它返回到将 1 加到 i(现在是 10)直到它达到 15。然后它将 15 加倍并且循环停止。我需要添加 5、10、15 和 20。我该如何修复现在的循环?

最佳答案

def sum_upto_divisible(x,div1):
    if div1 < 0 :
        div1 = -div1
    i=0
    s=0
    while i < x:
        s += i
        i += div1
    return s

关于python - 在 python 中使用 while 循环将所有可被 y 整除的数字 0 到 x 求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712257/

相关文章:

c# - "Use of unassigned local variable"错误 C#,"while"命令

python - 使用 Fast/Faster-RCNN 在 C++ 上制作对象检测器的最简单方法是什么?

python - 为什么某些 Unix 命令在从 Python 内部调用时不起作用? (找不到命令)

python - 如何检查并引发没有命令行参数的错误

c++ - while循环if和else

java - java中如何停止while循环?

python - numpy 中的超对角非方矩阵?

python - 转换为 float 而不舍入小数位

c - 在 C 中重新启动嵌套循环的理想方法?

php - 在表格中并排显示图像