[英]Function digits(n) that returns how many digits the number has , returns a random value in python
The function digits, in the while loop - while (n > 0) returns 325 326 327 and 1 as the count value and if I use while (n > 1) it returns the correct number count.在while循环中的函数digits - while (n > 0) 返回 325 326 327 和 1 作为计数值,如果我使用 while (n > 1) 它返回正确的数字计数。 Any logical reason for this behavior?
这种行为的任何合乎逻辑的原因?
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n / 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
There is a difference between /
and //
. /
和//
之间存在差异。
/
does the normal division given an accurate answer upto 15 decimal places in python. /
在 python 中给出最多 15 个小数位的准确答案的正常除法。 However, //
is the floor division method where only the quotient of the division is returned.但是,
//
是只返回除法的商的地板除法方法。
try to replace:尝试替换:
n = n / 10
with this:有了这个:
n = n // 10
If you divide something by 10 it will always be larger than 0, a quicker way would be:如果你除以 10,它总是大于 0,一个更快的方法是:
def digits(n):
return len(str(n))
Correct Code正确的代码
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n//10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
Logic being used We're using floor division instead of normal one because normal one will make the loop take very much time but return nothing so here, we'll use floor division until n gets smaller than 10 till then the count will get increasing by 1正在使用的逻辑我们使用楼层除法而不是普通的除法,因为正常的除法会使循环花费很长时间但不返回任何内容,所以在这里,我们将使用楼层除法,直到 n 小于 10,然后计数将增加1
For ex: We take 25 as an input例如:我们以 25 作为输入
25 // 10 = 2 count gets 1 25 // 10 = 2计数得到 1
2 // 10 = inputs gets smaller than zero count increases by 1 until condition is satisfied so now the count is 2 2 // 10 = 输入小于零计数增加 1 直到条件满足,所以现在计数为 2
Hope this helps :)希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.