编写约简分数的函数
时间: 2023-09-25 14:12:29 浏览: 119
以下是一个简单的 Python 函数,用于将分数约简为最简形式:
```python
def reduce_fraction(numerator, denominator):
"""
约简分数
:param numerator: 分子
:param denominator: 分母
:return: 约简后的分数元组 (numerator, denominator)
"""
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
# 如果分母为0,直接返回(0, 1)
if denominator == 0:
return 0, 1
# 如果分子为0,直接返回(0, 1)
if numerator == 0:
return 0, 1
# 计算分子和分母的最大公约数
g = gcd(numerator, denominator)
# 约简分数
numerator //= g
denominator //= g
return numerator, denominator
```
使用示例:
```python
>>> reduce_fraction(4, 6)
(2, 3)
>>> reduce_fraction(10, 25)
(2, 5)
>>> reduce_fraction(0, 5)
(0, 1)
>>> reduce_fraction(3, 0)
(0, 1)
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)