如何计算Python中的位数? [英] How to count the number of digits in Python?

查看:83
本文介绍了如何计算Python中的位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来计算给定数字中的位数.这是我的功能:

I am trying to write a function that counts the number of digits in a given number. This is my function:

def num_digits(n):
    """
    >>> num_digits(12345)
    5
    >>> num_digits(0)
    1
    >>> num_digits(-12345)
    5
    """
    count = 0
    while n > 0:
        if n == 0:
            count += 1
        count += 1
        n = n/10

    return count

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

但是这个功能不起作用.while 循环的条件应该是什么?

But this function is not working. What should the condition be for the while loop?

推荐答案

答案如下:

def num_digits(n):
    """
    >>> num_digits(12345)
    5
    >>> num_digits(0)
    1
    >>> num_digits(-12345)
    5
    """
    count = 0
    if n == 0:
        return 1
    
    if n < 0:
        n *= -1

    while n != 0:
        count += 1
        n = n // 10

    return count

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

这篇关于如何计算Python中的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆