-1
我的想法是接受一个数字作为输入,也许1.00
,然后乘以常量。在Python浮点操作中将小数位数限制为2
随后它被传递给一个函数来确定它是否是一个有效的回文。
如果不是这种情况,数字将逐渐增加,直到达到有效的回文数 - 但是,我想将探索空间限制在小数点后第二位。
也就是说1.01
是有效输出,但是1.001
不是。
下面的代码执行上面描述的过程,注意当前输出通常无效,溢出到更小的小数空间,即1.00001
等等。
操作的小数位数如何限制为2?
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])
candidrome = trial + (trial * 0.15)
print(candidrome)
# check whether we have a Palindrome
while not isPalindrome(candidrome):
candidrome += 0.01
if isPalindrome(candidrome):
print("It's a Palindrome! " + str(candidrome))
的解决方案建议here似乎不工作:
# check whether we have a Palindrome
while not isPalindrome(format(round(candidrome,2))):
candidrome += 0.01
[限制花车到小数点点]的可能的复制(HTTPS:/ /stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) –
所以 - 我试过这个解决方案 - 我在OP中引用它 –
您可以打印并发布数字while循环? – YiFei