使用python计数输入的位数 [英] Counting number of digits of input using python

查看:183
本文介绍了使用python计数输入的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算输入的位数。但是,每当我输入 10 11 或任何两位数字时,输出为 325 。为什么它不起作用?

I am trying to count the number of digits of an input. However, whenever I input 10 or 11 or any two digit number, the output is 325. Why doesn't it work?

inputnumber = int(input())
countnumber = inputnumber
digitcount = 0
while countnumber > 0:
    digitcount += 1
    countnumber = countnumber/10

print(digitcount) 
# result is 325 when input is 10 or 11


推荐答案

您的错误主要发生在这里:

Your error mainly happened here:

countnumber=countnumber/10

您打算进行整数除法。 Python 3 中的单斜杠除法始终是 float或 real除法,它会在需要时产生一个float值和一个小数部分。

Note that you are intending to do integer division. Single-slash division in Python 3 is always "float" or "real" division, which yields a float value and a decimal part if necessary.

将其替换为双斜杠除法,即整数除法: countnumber = countnumber // 10 。在这种情况下,每次执行整数除法时,都会切除最右边的数字。

Replace it with double-slash division, which is integer division: countnumber = countnumber // 10. Each time integer division is performed in this case, the rightmost digit is cut.

您还必须注意输入是否为0。数字0被认为是一位,而不是零。

You also have to watch out if your input is 0. The number 0 is considered to be one digit, not zero.

这篇关于使用python计数输入的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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