Python中的浮点数

9 投票
7 回答
52103 浏览
提问于 2025-04-16 08:28

我正在通过《Learn Python The Hard Way》学习Python,遇到了一些问题:

你注意到数学结果好像“错”了吗?这里没有分数,只有整数。想知道为什么,可以去查一下什么是“浮点数”。

我在这里读过关于浮点数的内容:http://docs.python.org/tutorial/floatingpoint.html

我还搞不清楚怎么输出浮点数,我想过用 round(3 + 3, 2) 来实现。

这样做对吗?

7 个回答

2

3 是一个整数。

3.0 是一个浮点数。

>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>

round() 函数:

这个函数可以把一个数字四舍五入到指定的小数位数(默认是0位)。无论如何,它总是会返回一个浮点数。

所以在你的例子中,返回的是 6.0。

5

把一个值传给 float() 这个构造函数的话,如果可以的话,它会把这个值变成一个 float 类型。

print float(2)
print float('4.5')

可以使用字符串插值或者格式化的方法来显示这些值。

print '%.3f' % 4.53
8

对于浮点数,你在数字后面加一个点,然后加一个零(如果这个数字是整数的话)。

比如这样:

1.0 <---- 这是浮点数。

1 <------- 这是整数。

这就是Python是怎么理解它们的。

if my_answer != your_question:
    print "I did not understand your question. Please rephrase it."
else:
    print "Good luck. Python is fun."

我同意rohit的看法,其实那个零并不是必须的。虽然对初学者来说,这样写会更简单。

撰写回答