2017-09-23 36 views
0

我有一個產生以下輸出一個Python腳本:強制執行數字輸出至少有兩個尾隨小數,包括尾隨零

31.7 
31.71 
31.72 
31.73 
31.74 
31.75 
31.76 
31.77 
31.78 
31.79 
31.8 
31.81 
31.82 
31.83 
31.84 
31.85 
31.86 
31.87 
31.88 
31.89 
31.9 
31.91 

請注意編號31.731.831.9

我的腳本的目的是確定數字迴文,如1.01

與(以下轉載)腳本的問題是,它會評估數字迴文,如1.1爲有效─然而 - 這是認爲在這種情況下,有效的輸出。

有效輸出需要精確到兩個小數位數。

如何強制數字輸出至少有兩個尾隨小數位,包括尾隨零?

import sys 

# This method determines whether or not the number is a Palindrome 
def isPalindrome(x): 
    x = str(x).replace('.','') 
    a, z = 0, len(x) - 1 
    while a < z: 
     if x[a] != x[z]: 
      return False 
     a += 1 
     z -= 1 
    return True 

if '__main__' == __name__: 

    trial = float(sys.argv[1]) 

    operand = float(sys.argv[2]) 

    candidrome = trial + (trial * 0.15) 

    print(candidrome) 
    candidrome = round(candidrome, 2) 

    # check whether we have a Palindrome 
    while not isPalindrome(candidrome): 
     candidrome = candidrome + (0.01 * operand) 
     candidrome = round(candidrome, 2) 
     print(candidrome) 

    if isPalindrome(candidrome): 
     print("It's a Palindrome! " + str(candidrome)) 
+0

的可能的複製[打印浮到n位小數包括末尾的0](https://stackoverflow.com/questions/8568233/print-float-to-n-小數位 - 包括 - 尾 - 零) –

回答

1

您可以使用內置的format功能。 .2指的是數字的位數,而f指的是「浮點數」。

if isPalindrome(candidrome): 
    print("It's a Palindrome! " + format(candidrome, '.2f')) 

或者:

if isPalindrome(candidrome): 
    print("It's a Palindrome! %.2f" % candidrome) 
+0

這是否會將它變成一個字符串? –

+0

@ s.matthew.english:是的。像'格式(0.666666,'.2f')''會返回''0.67''。 –

+0

但我需要它作爲一個浮點數,所以我可以管回到函數並使其成爲迴文 –

1

試試這個,而不是str(x)

twodec = '{:.2f}'.format(x) 
+0

我仍然看到有害的非尾隨零點,就像這個'3.2' –

+0

沒有 - 我的錯誤 - 這實際上是正確的 –

0

你可以試試這個:

data = """ 
    1.7 
    31.71 
    31.72 
    31.73 
    """ 
new_data = data.split('\n') 
palindromes = [i for i in new_data if len(i) > 3 and i.replace('.', '') == i.replace('.', '')[::-1]] 
0
x = ("%.2f" % x).replace('.','') 
+0

只有代碼的答案是不鼓勵的,因爲它們沒有解釋他們如何解決問題中的問題。考慮更新你的答案,以解釋它做了什麼,以及它如何解決問題 - 這不僅有助於OP,而且還有其他類似問題。請回顧[如何寫出一個好的答案](https://stackoverflow.com/help/how-to-answer) – FluffyKitten