Python将分数转换为十进制

Kar*_*tik 10 python

我想在python中转换1/2,这样当我说打印x(其中x = 1/2)时它返回0.5

我正在寻找最基本的方法,而不使用任何拆分函数,循环或映射

我试过漂浮(1/2),但我得到0 ...有人可以解释我为什么以及如何解决它?

是否可以在不修改变量x = 1/2的情况下执行此操作?

谢谢

Ant*_*Ant 26

在python 3.x中,任何分区都返回一个浮点数;

>>> 1/2
0.5
Run Code Online (Sandbox Code Playgroud)

要在python 2.x中实现它,你必须强制浮动转换:

>>> 1.0/2
0.5
Run Code Online (Sandbox Code Playgroud)

或从"未来"进口分部

>>> from __future__ import division
>>> 1/2
0.5
Run Code Online (Sandbox Code Playgroud)

额外的:没有内置的分数类型,但官方库中有:

>>> from fractions import Fraction
>>> a = Fraction(1, 2) #or Fraction('1/2')
>>> a
Fraction(1, 2)
>>> print a
1/2
>>> float(a)
0.5
Run Code Online (Sandbox Code Playgroud)

等等...

  • 更正 - 在Python3中,`/`执行浮动除法,`//`执行int除法; 在Python2中,根据参数,`/`可以是float除法(如果至少有一个arg是float)或int(如果所有args都是int) (4认同)

Gre*_*ill 8

您可能正在使用Python 2.您可以使用以下方法"修复"除法:

from __future__ import division
Run Code Online (Sandbox Code Playgroud)

在脚本的开头(在任何其他导入之前).默认情况下,在Python 2中,/运算符在使用整数操作数时执行整数除法,这会丢弃结果的小数部分.

这已在Python 3中进行了更改,因此/始终是浮点除法.new //运算符执行整数除法.

  • 您正在谈论什么"输入"?请详细说明你在做什么. (2认同)

小智 7

或者,您可以通过指定小数或乘以1.0来强制浮点除法.例如(从python解释器内部):

>>> print 1/2
0
>>> print 1./2
0.5
>>> x = 1/2
>>> print x
0
>>> x = 1./2
>>> print x
0.5
>>> x = 1.0 * 1/2
>>> print x
0.5
Run Code Online (Sandbox Code Playgroud)

编辑:看起来我在打字响应时打得很好:)


Bri*_*ton 6

如果输入是字符串,则可以直接在输入上使用小数:

from fractions import Fraction

x='1/2'
x=Fraction(x)  #change the type of x from string to Fraction
x=float(x)     #change the type of x from Fraction to float
print x
Run Code Online (Sandbox Code Playgroud)