生成一个分数类
时间: 2023-08-14 16:07:18 浏览: 187
好的,以下是一个简单的分数类的示例代码:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def simplify(self):
gcd = self.get_gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
def get_gcd(self, a, b):
if b == 0:
return a
else:
return self.get_gcd(b, a % b)
def add(self, other):
new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
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 - other.numerator * self.denominator
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):
new_numerator = self.numerator * other.denominator
new_denominator = self.denominator * other.numerator
result = Fraction(new_numerator, new_denominator)
result.simplify()
return result
```
这个分数类包含四种基本运算(加、减、乘、除)以及一个化简分数的方法。你可以通过以下代码进行测试:
```python
f1 = Fraction(3, 6)
f2 = Fraction(2, 4)
print(f1.add(f2)) # 输出 1/1
print(f1.subtract(f2)) # 输出 0/1
print(f1.multiply(f2)) # 输出 1/4
print(f1.divide(f2)) # 输出 1/1
```
阅读全文