【发布时间】:2021-12-07 10:58:37
【问题描述】:
我写了一个函数叫count_digit:
# Write a function which takes a number as an input
# It should count the number of digits in the number
# And check if the number is a 1 or 2-digit number then return True
# Return False for any other case
def count_digit(num):
if (num/10 == 0):
return 1
else:
return 1 + count_digit(num / 10);
print(count_digit(23))
我得到325 作为输出。为什么会这样,我该如何纠正?
【问题讨论】:
-
使用 Python 2 或 3?
-
return len(str(num)) -
@LarrytheLlama,OP 可能正在尝试执行递归函数。这很有效
-
你应该使用整数除法(
//而不是/)或者这里建议的更简单的方法。 -
数字中的位数究竟是什么意思?