求小数点后的位数

编程入门 行业动态 更新时间:2024-10-24 14:18:40
本文介绍了求小数点后的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to write a Python 2.5.4 code to write a function that takes a floating-point number x as input and returns the number of digits after the decimal point in 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 循环中的打印语句仅用于调试目的.

The print statements within the while loop are only for debugging purposes.

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

Now when I run this code, I get the following as output.

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.

The final value of count as returned by this function is 17.

如何修改这段代码才能达到我们想要的效果?

How to modify this code in order to achieve our desired result?

推荐答案

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

Here's a shortcut that you might like:

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

更多推荐

求小数点后的位数

本文发布于:2023-10-14 22:30:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数点   位数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!