【问题标题】:Restrict number of decimal places to two in Python float operations在 Python 浮点运算中将小数位数限制为两位
【发布时间】: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

【问题讨论】:

标签: python floating-point decimal


【解决方案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])

    candidrome = trial + (trial * 0.15)

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


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

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

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2022-01-11
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多