如何在Python中生成float?

2024-04-25 19:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我这样做了:

width =  14
height = 6
aspect = width/height

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


Tags: 声明floatwidthheight新手aspect
1条回答
网友
1楼 · 发布于 2024-04-25 19:26:01

有很多选择:

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一样。你知道吗

相关问题 更多 >