【问题标题】:Why worng answer in counting digit in numbers with python3 with right logic?为什么用 python3 用正确的逻辑计算数字的错误答案?
【发布时间】:2020-08-03 05:37:26
【问题描述】:

我在编辑器中编写了这段代码:

#!/usr/bin/env python3


def digits(n):
    count = 0
    if n == 0:
      count = 1
    while n > 0:
      n /= 10
      count += 1
    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

但我越来越喜欢:

325
326
327
1

这是错误的逻辑还是,我错过了什么?

【问题讨论】:

    标签: python python-3.x logic


    【解决方案1】:

    /= performs floating-point division. 使用//= 进行整数除法。

    def digits(n):
        count = 0
        if n == 0:
            count = 1
        while n > 0:
            n //= 10
            count += 1
        return count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2016-08-24
      • 2018-05-28
      • 2016-09-24
      • 2018-03-05
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多