Skip to main content
 首页 » 编程设计

python之如何在 Python 中制作 float

2025年05月04日13三少

如果我这样做:

width =  14 
height = 6 
aspect = width/height 

我得到的结果是 aspect = 2 而不是 2.33。我是 Python 的新手,希望它会自动转换它;我错过了什么吗?我需要显式声明一个 float 吗?

请您参考如下方法:

有很多选择:

aspect = float(width)/height 

或

width = 14.       # <-- The decimal point makes width a float. 
height 6 
aspect = width/height 

或

from __future__ import division   # Place this as the top of the file 
width =  14 
height = 6 
aspect = width/height 

在 Python2 中,整数除法返回一个整数(或 ZeroDivisionError)。在 Python3 中,整数除法可以返回 float 。

from __future__ import division 

告诉 Python2 使除法的行为与在 Python3 中一样。