我有一個產生以下輸出一個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.7
,31.8
,31.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))
的可能的複製[打印浮到n位小數包括末尾的0](https://stackoverflow.com/questions/8568233/print-float-to-n-小數位 - 包括 - 尾 - 零) –