首页 > 编程知识 正文

Python 程序:计算数字位数

时间:2023-11-24 15:33:38 阅读:308824 作者:MOLR

编写一个 Python 程序,使用 While 循环、函数和递归来计算数字的位数

使用 While 循环计算数字位数的 Python 程序

这个 python 程序允许用户输入任何正整数。然后,它将给定的数字分成单个数字,并使用 Python While Loop 对这些单个数字进行计数。

# Python Program to Count Number of Digits in a Number using While loop

Number = int(input("Please Enter any Number: "))
Count = 0
while(Number > 0):
    Number = Number // 10
    Count = Count + 1

print("n Number of Digits in a Given Number = %d" %Count)

这个 Python 程序允许用户输入任何正整数。然后,该数字被分配给数字变量。

接下来,在 Python While Loop 中的条件确保给定的数字大于 0(表示正整数且大于 0)

在本 Python 中,计数数字中的数字,用户输入的值:数字= 9875,计数= 0

第一次迭代

编号=编号// 10 => 9875 //10 编号= 987

计数=计数+ 1 => 0 + 1 计数= 1

第二次迭代:从第一次 Python 迭代开始,数字和计数的值都变成了数字= 987 和计数= 1

编号= 987 // 10 编号= 98

计数= 1 + 1 计数= 2

第三次迭代:从第二次迭代开始,数字= 98,计数= 2

数量= 98 // 10 数量= 9

计数= 2 + 1 计数= 3

第四次迭代:对于第四次迭代,数字= 9,计数= 3

Number = 9 // 10 Number = 0

计数= 3 + 1 计数= 4

这里数字= 0。因此,while 循环中出现的情况会失败。

最后一个打印语句使用计数变量作为输出,打印给定数字中的位数。所以,给定变量 9875 的输出是 4。

使用函数计算数字位数的 Python 程序

这个 Python 程序允许用户输入任意正整数。然后,它将给定的数字分成单个数字,并使用函数对这些单个数字进行计数。

# Python Program to Count Number of Digits in a Number using Functions

def Counting(Number):
    Count = 0
    while(Number > 0):
        Number = Number // 10
        Count = Count + 1
    print("n Number of Digits in a Given Number = %d" %Count)

Counting(1234)

运筹学

def Counting(Number):
    Count = 0
    while(Number > 0):
        Number = Number // 10
        Count = Count + 1
    return Count

Number = int(input("Please Enter any Number: "))
Count = Counting(Number)
print("n Number of Digits in a Given Number = %d" %Count)
Please Enter any Number: 123456789

 Number of Digits in a Given Number = 9

当它到达 Counting (Number)行 python 程序时,那么编译器立即跳转到下面的函数:

def Counting(Number):

最后一行以返回计数语句结束。

用递归计算数字位数的 Python 程序

这个 Python 程序将给定的数字分成单个数字,并使用递归对这些单个数字进行计数。

Count = 0
def Counting(Number):
    global Count
    if(Number > 0):
        Count = Count + 1
        Counting(Number//10)
    return Count

Number = int(input("Please Enter any Number: "))
Count = Counting(Number)
print("n Number of Digits in a Given Number = %d" %Count)
Please Enter any Number: 12345

 Number of Digits in a Given Number = 5

在计数(数字)函数定义中,下面的语句有助于用更新的值递归调用函数。

Counting(Number//10)

如果您错过此语句,在完成第一行后,它将终止。例如

数字= 1234

那么输出为 1。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。