gpt4 book ai didi

python - 计算数字总和的调试函数

转载 作者:行者123 更新时间:2023-11-28 22:09:34 24 4
gpt4 key购买 nike

我刚刚开始调试。任务是查找和调整 2 个函数的错误代码:一个计算奇数位的和,而另一个计算偶数位。

我已经找到问题所在,但不知道之后该怎么办。

def sum_odd_digits(number):
dsum = 0
# only count odd digits
while number % 2 != 0:
# add the last digit to the sum
digit = number % 10
dsum = dsum + digit
# divide by 10 (rounded down) to remove the last digit
number = number // 10
return dsum

def sum_even_digits(number):
m = 1 # the position of the next digit
dsum = 0 # the sum
while number % (10 ** m) != 0:
# get the m:th digit
digit = (number % (10 ** m)) // (10 ** (m - 1))
# only add it if even:
if digit % 2 == 0:
dsum = dsum + digit
m = m + 1
return dsum

对于 sum_odd_digits 函数,如果奇数位在偶数位之前,它会给出错误的值(例如 129 只返回 9,而不是 10)。对于 sum_even_digits 函数,存在无限循环,我不知道如何解决这个问题。

最佳答案

def sum_odd_digits(number):
dsum = 0

while number > 0:
# add the last digit to the sum if it is odd
digit = number % 10
if digit%2!=0: # implies odd digit
dsum = dsum + digit
# divide by 10 (rounded down) to remove the last digit
number = number // 10
return dsum

def sum_even_digits(number):
dsum = 0

while number > 0:
# add the last digit to the sum if it is even
digit = number % 10
if digit%2==0: # implies even digit
dsum = dsum + digit
# divide by 10 (rounded down) to remove the last digit
number = number // 10
return dsum

关于python - 计算数字总和的调试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57601825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com