簡體   English   中英

返回數字有多少位的函數digits(n),在python中返回一個隨機值

[英]Function digits(n) that returns how many digits the number has , returns a random value in python

在while循環中的函數digits - while (n > 0) 返回 325 326 327 和 1 作為計數值,如果我使用 while (n > 1) 它返回正確的數字計數。 這種行為的任何合乎邏輯的原因?

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

///之間存在差異。

/在 python 中給出最多 15 個小數位的准確答案的正常除法。 但是, //是只返回除法的商的地板除法方法。

嘗試替換:

n = n / 10

有了這個:

n = n // 10

如果你除以 10,它總是大於 0,一個更快的方法是:

def digits(n):
    return len(str(n))

正確的代碼

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

正在使用的邏輯我們使用樓層除法而不是普通的除法,因為正常的除法會使循環花費很長時間但不返回任何內容,所以在這里,我們將使用樓層除法,直到 n 小於 10,然后計數將增加1

例如:我們以 25 作為輸入

  • 25 // 10 = 2計數得到 1

  • 2 // 10 = 輸入小於零計數增加 1 直到條件滿足,所以現在計數為 2

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM