如何使用Python查找给定数字中的位数?
在此程序中,我们必须找到用户指定的整数位数。
例如
用户输入:123,输出:3
用户输入:1987,输出:4
算法
Step 1: Take Integer value as input value from the userStep 2: Divide the number by 10 and convert the quotient into Integer typeStep 3: If quotient is not 0, update count of digit by 1Step 4: If quotient is 0, stop the countStep 5: STOP
范例程式码
x = int(input("用户输入: "))
count_of_digits = 0
while x > 0:
x = int(x/10)
count_of_digits += 1
print("位数: ",count_of_digits)输出结果用户输入: 123 位数: 3 用户输入: 1987 位数: 4
解释
当我们将数字除以10并将结果转换为int类型时,将删除单位的位数。因此,将结果每次除以10,就可以得到整数中的位数。一旦结果变为0,程序将退出循环,我们将获取整数中的位数。
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短