函数digits(n)表示returns这个数字有多少位,returnspython中的一个随机值

Function digits(n) that returns how many digits the number has , returns a random value in python

while 循环中的函数数字 - while (n > 0) returns 325 326 327 和 1 作为计数值,如果我使用 while (n > 1) 它 returns正确的数字计数。这种行为有什么合乎逻辑的原因吗?

def digits(n):
    count = 0
    if n == 0:
      return 1
    while (n > 0):
        count += 1
        n = n / 10
    return count
    
print(digits(25))   # Should print 2
print(digits(144))  # Should print 3
print(digits(1000)) # Should print 4
print(digits(0))    # Should print 1

///有区别。

/ 给出 python 中最多 15 位小数的准确答案进行正常除法。但是,//是只返回除法商的底除法。

尝试替换:

n = n / 10

有了这个:

n = n // 10

如果你将某个数除以 10,它总是大于 0,更快的方法是:

def digits(n):
    return len(str(n))

正确的代码

def digits(n):
    count = 0
    if n == 0:
      return 1
        while (n > 0):
            count += 1
            n = n//10
        return count
        
    print(digits(25))   # Should print 2
    print(digits(144))  # Should print 3
    print(digits(1000)) # Should print 4
    print(digits(0))    # Should print 1

正在使用的逻辑 我们使用楼层划分而不是普通划分,因为普通划分会使循环花费很多时间,但 return 这里没有, 我们将使用 floor 除法,直到 n 小于 10,然后计数将增加 1

例如:我们将 25 作为输入

  • 25 // 10 = 2 count 得到 1

  • 2 // 10 = 输入小于零 count 增加 1 直到满足条件,所以现在计数为 2

希望对您有所帮助:)