如何在过载功能中更正浮点符号

我正在使用应该除法,幂和浮点运算符重载的代码。我似乎在编辑原始代码时遇到困难,因此答案不是浮点格式,而是整数或字符串。

我不断得到的输出是:

我的第一个理性是2/7#正确

它的立方体是8.0 / 343.0#不正确

它的近似浮点值为0.2857142857142857#正确

我的第二个有理数是1/3#正确

我的第一个有理数是第二个有理数#incorrect的2 / 2.333333333333333倍

我应该得到的输出是:

我的第一个理性是2/7

它的立方体是8/343

其近似浮点值为0.2857142857142857

我的第二个有理数是1/3

我的第一个有理数比第二个大6/7倍

我尝试将str()和int()放在代码中某些变量的前面,但是它说那些操作数不适用于“ /”和“ **”

从代码中删除浮点数时,出现以下错误消息:

回溯(最近通话最近一次):

文件“ /Users/******/Desktop/ration/rationaluse.py”,第10行,在     print(“我的第一个有理数”,r1 / r2,“比第二个有理数大”)

文件“ /Users/*****/Desktop/ration/rational.py”,第15行,在 truediv 中     返回Rational(self.numerator,self.denominator *(other)) TypeError:*:“ int”和“ Rational

不支持的操作数类型
'''The file that needs to be edited: '''
from sys import *
class Rational:
    def __init__(self,n,d):
        if d == 0:
            print ("Invalid Denominator!")
        else:
            self.numerator = n
            self.denominator = d
    def __repr__(self):
        return str(self.numerator) + "/" + str(self.denominator)
    def __str__(self):
        return str(self.numerator) + "/" + str(self.denominator)

    def __truediv__(self,other):
        return Rational(self.numerator,self.denominator * float(other))
    def __pow__(self,other):
        return Rational(self.numerator ** float(other),self.denominator ** float(other))
    def __float__(self):
        return self.numerator / self.denominator

'''给出的用于按原样打印输出且无法编辑的文件'''     来自合理进口*

r1 = Rational(2,7)
print("My first rational is",r1)
print("Its cube is",r1**3)
print("Its approximate floating point value is",float(r1))

r2 = Rational(1,3)
print("My second rational is",r2)
print("My first rational is",r1/r2,"times larger than the second one")
sothis2000 回答:如何在过载功能中更正浮点符号

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3120657.html

大家都在问