在Python中使用for循环计算位数

问题描述 投票:0回答:3

我想计算任何数字的位数,而不将数字转换为字符串,也不使用 for 循环。有人可以建议如何做到这一点吗?

num = int(input("Enter any number : "))
temp = num
count = 0
for i in str(temp):
    temp = temp // 10
    count += 1
print(count)
python string loops for-loop numbers
3个回答
0
投票

如果你坚持使用

input
,你就无法摆脱这个功能会提示
String
的事实。至于
for
循环,只需计算输入字符串中的字符数即可:

num = input("Enter any number : ")                                                                       
print(len(num))  

0
投票

您不必创建

temp
变量,因为
num
已包含输入。

如果只输入数字,您可以首先使用模式检查,然后获取字符串的长度,而不使用任何循环。

import re

inp = input("Enter any number : ")
m = re.match(r"\d+$", inp)

if m:
    print(len(m.group()))
else:
    print("There we not only digits in the input.")

0
投票

希望这有帮助,尽管这只适用于整数 int 类型,即非小数点值

import math as m
n:int=int(input())
print(int(m.log10(m))+1)
© www.soinside.com 2019 - 2024. All rights reserved.