首页 > 解决方案 > 如何创建一个可以加减有理数的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。感谢您的所有帮助,但我不知道您的意思或如何解决它。

标签: 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)

编辑:我添加了如何使用该类的示例。


推荐阅读