设计并实现一个减法和乘法分数计算器,输入分数形式a/b其中a,b为整数,计算结果也是a/b的表现形式
时间: 2024-10-13 15:17:21 浏览: 27
设计一个简单的分数计算器,我们可以先定义一个`Fraction`类,用于表示分数,包含两个私有属性`numerator`(分子)和`denominator`(分母)。然后提供加、减、乘、除的方法来进行运算。为了保持分数的形式,即结果始终为最简形式,我们还需要在运算结束后检查并简化分数。
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = abs(denominator)
def simplify(self):
gcd = self.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def gcd(self, a, b):
while b != 0:
a, b = b, a % b
return a
def add(self, other):
new_numerator = self.numerator * other.denominator + self.denominator * other.numerator
new_denominator = self.denominator * other.denominator
result = Fraction(new_numerator, new_denominator)
result.simplify()
return result
def subtract(self, other):
new_numerator = self.numerator * other.denominator - self.denominator * other.numerator
new_denominator = self.denominator * other.denominator
result = Fraction(new_numerator, new_denominator)
result.simplify()
return result
def multiply(self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
result = Fraction(new_numerator, new_denominator)
result.simplify()
return result
def divide(self, other):
if other.denominator == 0:
raise ZeroDivisionError("Cannot divide by zero")
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
result = Fraction(new_numerator, new_denominator)
result.simplify()
return result
# 使用示例
f1 = Fraction(4, 6)
f2 = Fraction(3, 5)
print(f1.add(f2)) # 输出: Fraction(19, 30) (已简化)
```
在这个例子中,用户可以创建`Fraction`对象,然后调用相应的`add`, `subtract`, `multiply`, 或 `divide` 方法来进行运算,并自动将结果保持在最简形式。
阅读全文