You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Range函数未按定义跳过数值的奇数求和问题

计算指定范围内奇数之和的问题解决

你的代码当前遍历了1到num的所有整数并累加,没有过滤偶数,所以得到的是所有数的总和而非奇数和。下面是几种解决方法:

方法一:直接生成奇数序列遍历

修改range的步长为2,从1开始,这样生成的序列本身就是奇数:

num = 5

def sumOfOdds():
    total = 0  # 避免使用内置函数名sum作为变量
    for i in range(1, num + 1, 2):
        total += i
    print(total)

sumOfOdds()

range(1, num+1, 2)会生成1, 3, 5这样的奇数序列,直接累加即可得到结果。

方法二:循环内判断奇数

遍历所有数,通过取余操作判断是否为奇数,仅累加符合条件的数:

num = 5

def sumOfOdds():
    total = 0
    for i in range(1, num + 1):
        if i % 2 != 0:  # 奇数除以2余数不为0
            total += i
    print(total)

sumOfOdds()

方法三:用数学公式优化(无需循环)

1到n的奇数和有现成的数学公式:奇数和 = ((n + 1) // 2)²,比如n=5时,((5+1)//2)²=3²=9,直接计算更高效:

num = 5

def sumOfOdds():
    odd_count = (num + 1) // 2
    total = odd_count ** 2
    print(total)

sumOfOdds()

这个公式对奇数和偶数的n都适用,比如n=4时,((4+1)//2)²=2²=4,对应1+3=4,结果正确。


内容的提问来源于stack exchange,提问作者Pb N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:35:23