Python中的 as_integer_ratio() 用于减少给定有理数的分数
给定一个有理数 d,打印得到 d 的缩减分数。
例子:
Input : d = 2.5
Output : 5/2
Explanation: 5/2 gives 2.5 which is the reduced form
of any fraction that gives 2.5
Input : d = 1.5
Output : 3/2
as_integer_ratio()函数Python:
返回一对整数,其比率与原始浮点数完全相等且分母为正。
Syntax:
float. as_integer_ratio()
Return Value:
Tuple (a pair of integers)
Errors:
Raises OverflowError on infinities and a ValueError on NaNs.
在Python中,我们有一个内置函数as_integer_ratio() ,它打印任何给定有理数 d 的缩减分数形式。我们需要将它存储在任何变量中,然后打印存储分数的第 0 个索引和第一个索引。
Python3
# function to print the fraction of
# a given rational number
def reducedfraction(d):
# function that converts a rational number
# to the reduced fraction
b = d.as_integer_ratio()
# reduced the list that contains the fraction
return b
# driver code
b = reducedfraction(2.5)
print (b[0], "/", b[1])
输出:
5 / 2