【发布时间】:2018-03-04 15:09:44
【问题描述】:
我的想法是接受一个数字作为输入,也许是1.00,然后将它乘以一个常数。
随后它被传递给一个函数来确定它是否是一个有效的回文数。
如果不是,则该数字将逐渐增加,直到达到有效回文 - 但是,我想将探索空间限制在小数点后第二位。
也就是说1.01是有效输出,但1.001不是。
随后的代码执行上述过程,但需要注意的是当前输出通常无效,会溢出到更小的小数位,即1.00001 等等。
如何将运算的小数位数限制为两位?
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
【问题讨论】:
-
所以-我尝试了该解决方案-我在 OP 中引用了它
-
你能在while循环中打印并发布数字吗?
标签: python floating-point decimal