用python写一个程序,定义有理数类,并创建两个实例,从键盘输入有理数,完成有理数的相加、相乘
时间: 2024-10-26 18:02:20 浏览: 19
用Python写一个模拟qq聊天小程序的代码实例
当然可以,下面是一个简单的Python程序示例,用于定义一个有理数类(Rational),并实现了相加和相乘的功能:
```python
class Rational:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = abs(denominator)
# 定义相加函数
def add(self, other):
new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
# 定义相乘函数
def multiply(self, other):
new_numerator = self.numerator * other.numerator
new_denominator = self.denominator * other.denominator
return Rational(new_numerator, new_denominator)
# 创建两个Rational实例
num1 = input("请输入第一个有理数的分子 (numerator): ")
den1 = input("请输入第一个有理数的分母 (denominator, 非零): ")
num1 = int(num1)
den1 = int(den1)
num2 = input("请输入第二个有理数的分子 (numerator): ")
den2 = input("请输入第二个有理数的分母 (denominator, 非零): ")
num2 = int(num2)
den2 = int(den2)
# 确保分母不为0
if den1 == 0 or den2 == 0:
print("分母不能为0")
else:
num1_rational = Rational(num1, den1)
num2_rational = Rational(num2, den2)
# 相加
sum_result = num1_rational.add(num2_rational)
print(f"两数相加的结果为: {sum_result.numerator}/{sum_result.denominator}")
# 相乘
product_result = num1_rational.multiply(num2_rational)
print(f"两数相乘的结果为: {product_result.numerator}/{product_result.denominator}")
```
运行此程序后,用户将被提示输入两个有理数的分子和分母。然后程序会计算它们的和与积。
阅读全文