如果我这样做:
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 中一样。
关于python - 如何在 Python 中制作 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19742846/