python - Python中使用while true的位数

标签 python python-3.x

我正在 Python 3.6.1 上编写一个程序,用于计算用户给定数字的位数。我使用的是“while True”这句话,而不是函数或字符串,因为我还没有学会使用它们。这是我的代码:

number=int(input("Write number: ")) 
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break 
print("The number of digits is: ", cont)

我的问题是上面的代码不起作用,因为当我输入 123 时,程序给出的值是 326。我不知道我的代码出了什么问题,所以我该如何解决这个问题?

最佳答案

看看这个:

Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 123 / 10
12.3

是的,/ 是 Python 中的浮点除法,因此它不会执行您期望的操作。

如果在除以十之后立即插入 print(number),您可以看到实际发生的情况。它不断地进行除法,直到得到一个小到无法区分它和零的数字:

12.3
1.23
0.123
0.0123
0.00123
0.000123
1.23e-05
1.23e-06
1.23e-07
1.2300000000000001e-08
1.23e-09
1.2300000000000001e-10
1.2300000000000002e-11
1.2300000000000002e-12
1.2300000000000003e-13
1.2300000000000003e-14
1.2300000000000003e-15
:
1.2299999999999997e-307
1.2299999999999997e-308
1.23e-309
1.23e-310
1.23e-311
1.23e-312
1.23e-313
1.23e-314
1.23e-315
1.23e-316
1.23e-317
1.23e-318
1.23003e-319
1.23e-320
1.23e-321
1.24e-322
1e-323
0.0

您可以通过更改来解决此问题:

number=number/10

进入以下任一:

number = int(number / 10)
number = number // 10

这将进行整数除法,因此将在正确的步数后停止。

关于python - Python中使用while true的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44896111/

相关文章:

Python urllib2 强制 IPv4

javascript - Flask 返回重定向在删除后不起作用

python - Python 3 中每个条目后打印换行符

python - 如何将字符串中的 "\t"拆分为两个单独的字符 "\"和 "t"? (如何拆分转义序列?)

python - Python 中的全局变量和局部变量

python - Python open(file)的类型是什么

python - 如何使用属性 setter 作为回调

python - 单击 x 退出 python

python - SQLAlchemy 类跨文件,不创建表

python - 为什么 python 假设我的路径是项目根目录,这是两个目录级别?