python - 如何在 Python 中制作 float ?

标签 python

如果我这样做:

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/

相关文章:

python - Django 中的动态过滤器

python - 使用 Django 使用 RESTful API

python - 如何在OpenCV Python中的固定位置显示框架

python - 使用 MySQLdb 执行多个 SQL 查询

python - 如何在python输入中交换字母?

Python/Django - Django 模型的动态属性重载

python - 为什么 `pandas.read_csv` 不是 `pandas.DataFrame.to_csv` 的倒数?

python - 使用自定义混合类型创建枚举

Python 3.6 SSL - 使用 TLSv1.0 而不是 TLSv1.2 密码 -(2 种身份验证和自签名证书)

c++ - 在 C++ 中,CPython 字符串连接的等价物是什么?