简体   繁体   English

Python 数字计数器 function 无法正常工作

[英]Python digit counter function doesnt work properly

When I try to make a function that counts the digits in a number, it doesn't work properly, it doesn't show the number of digits,but some random numbers当我尝试制作一个 function 来计算数字中的位数时,它无法正常工作,它不显示位数,而是一些随机数

def count(number):
counter=0
while number>0:
    number/=10
    counter+=1
return counter

can you please tell me what I'm doing wrong?你能告诉我我做错了什么吗?

If we explore what your function is doing, it is just continuously dividing an input number by 10. In math, if you keep dividing a real number not equal to zero (I don't want to get into imaginary numbers) by another larger real number not equal to zero, the result will never equal zero - you will have an infinite list of numbers decreasing in size, getting infinitesimally small.如果我们探索您的 function 正在做什么,它只是将输入数字连续除以 10。在数学中,如果您继续将不等于零的实数(我不想进入虚数)除以另一个更大的实数number 不等于 0,结果永远不会等于 0 - 您将有一个无限的数字列表,其大小会逐渐减小,变得无限小。

For example if our number is 10, your function function will set number to:例如,如果我们的号码是 10,那么您的 function function 会将号码设置为:

10
1
.1
.01
.001
.0001
.00001
...

In programming (specifically python), this will continue until the float value is too small for python to differentiate from 0.0, and will return a "random" number.在编程(特别是 python)中,这将一直持续到浮点值太小以至于 python 无法与 0.0 区分开来,并将返回一个“随机”数字。

Another way to accomplish what you are trying to do would be to convert the number to a string and get the length of the string.完成您尝试做的事情的另一种方法是将数字转换为字符串并获取字符串的长度。

def count(number):
    counter = str(number)
return len(counter)

You can also use "floor division", which rounds the result of your division down to the nearest whole integer, if you want to keep your function in a purely mathematical domain.如果您想将 function 保持在纯数学域中,您还可以使用“地板除法”,将除法结果向下舍入到最接近的整数 integer。

def count(number):
    counter=0
    while number>0:
        number //= 10
        counter += 1
    return counter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM