查找小数点后的位数

2024-06-02 04:54:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个Python 2.5.4代码来编写一个函数,该函数以一个浮点数x作为输入,并返回x中小数点后的位数

这是我的代码:

def number_of_digits_post_decimal(x):
    count = 0
    residue = x -int(x)
    if residue != 0:
        multiplier = 1
        while int(multiplier * residue) != (multiplier * residue):
            count += 1
            multiplier = 10 * multiplier
            print count
            print multiplier
            print multiplier * residue
            print int(multiplier * residue)
            return count

print number_of_digits_post_decimal(3.14159)

while循环中的print语句仅用于调试目的。

现在,当我运行这段代码时,我得到以下输出。

1

10

1.4159

1

2

100

14.159

14

3

1000

141.59

141

4

10000

1415.9

1415

5

100000

14159.0

14158

6

1000000

141590.0

141589

7

10000000

1415900.0

1415899

8

100000000

14159000.0

14158999

9

1000000000

....

此函数返回的count的最终值是17。

如何修改此代码以达到预期的结果?


Tags: of函数代码numbercountpostintdecimal
2条回答

以下是您可能喜欢的快捷方式:

def num_after_point(x):
    s = str(x)
    if not '.' in s:
        return 0
    return len(s) - s.index('.') - 1

这很有趣!因此,如果运行以下命令:

x = 3.14159  
residue = x - int(x)  
print residue  

您将得到以下结果:

0.14158999999999988

这个十进制数实际上有17位。我发现覆盖它的唯一方法是避免做减法(这是错误的根本原因,从这里的不精确性可以看出)。因此,此代码应按您的预期工作:

def number_of_digits_post_decimal(x):  
    count = 0  
    residue = x -int(x)  
    if residue != 0:  
        multiplier = 1  
        while not (x*multiplier).is_integer():  
            count += 1  
            multiplier = 10 * multiplier  
        return count

这只会向右移动小数点,直到python将其标识为整数(它也会按您所需的次数向右移动)。您的代码实际上按您的预期工作,在减法过程中发生了一些意外的事情。希望这有帮助!

相关问题 更多 >