python - 如何创建一个可以加减有理数的python程序
问题描述
这是我的作业:
对于冗长的问题和带有小字的不良屏幕截图,我深表歉意。我是 Python 新手,我的老师不教,所以我尽可能多地从教科书中学习,但这个问题非常棘手,我知道我做错了。
这是我到目前为止所做的:
class rational_numbers:
def add(self, other):
def __init__ (self, numerator, denominator):
self.numerator = input(int("Please enter the numerator: "))
self.denominator = input(int("Please enter the denominator: "))
numerator = self.numerator * other.denominator + other.numerator * self.denominator
denominator = self.denominator * other.denominator
def mul(self, other):
def __init__ (self, numerator, denominator):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
def reduce(numerator, denominator):
if numerator == 0 :
return denominator
return gcd(b%a, a)
我试图尽可能地按照说明进行操作,并且我已经进行了研究并尝试了几天,但无济于事。任何帮助,将不胜感激!
编辑:我不是很聪明或擅长 python。感谢您的所有帮助,但我不知道您的意思或如何解决它。
解决方案
我认为您的课程会更好:
from math import gcd
class RationalNumber: # Use Camel Case for Class names
def __init__ (self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
red = self.reduce()
self.numerator = red.numerator
self.denominator = red.denominator
def add(self, other):
numerator = self.numerator * other.denominator + other.numerator * self.denominator
denominator = self.denominator * other.denominator
return RationalNumber(numerator, denominator)
def mul(self, other):
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return RationalNumber(numerator, denominator)
def reduce(self):
if self.numerator == 0 :
return 0
nd_gcd = gcd(self.denominator%self.numerator,self.numerator)
if nd_gcd == 1:
return self
return RationalNumber(int(self.numerator//nd_gcd),
int(self.denominator//nd_gcd))
half = RationalNumber(1,2)
quarter = RationalNumber(1,4)
three_quarters = half.add(quarter)
print( three_quarters.numerator, three_quarters.denominator)
three_quarters = three_quarter.reduce()
print( three_quarters.numerator, three_quarters.denominator)
编辑:我添加了如何使用该类的示例。
推荐阅读
- php - 在 PHP 中使用整数来消除间隙
- firebase - Big Query 中的 Firebase 事件重复数据删除 - 最佳做法?
- amazon-web-services - 无法编辑持久存储“s3” - 带有 s3 配置的三角帆存储
- sql - 如何在 sql 查询“mo_global.set_policy_context('S',orgid);”中在 oracle 中设置策略上下文
- python-3.x - 错误:命令的完整输出:使用 pip 安装 spaCy 时出错
- java - isNetworkConnected() Android Pie 9.0 的问题
- python - 如何在 python 中实现'sqlite3_busy_timeout'?
- firebase - 每次在firebase实时数据库中添加新孩子时,如何更新flutter应用程序中的列表
- python-3.x - 函数“collect_vertex_marginals”在文档示例中返回错误
- javascript - 如何使用 Jquery 从 Button 切换阅读更多内容?