python - 如何更正重载函数中的浮点表示法
问题描述
我正在使用一个应该与除法、幂和浮点运算符重载的代码。我似乎很难编辑我的原始代码,因此答案不是浮点格式,而是整数或字符串。
我不断得到的输出是:
我的第一个理性是 2/7 #正确
它的立方体是 8.0/343.0 #incorrect
它的近似浮点值为0.2857142857142857 #正确
我的第二个有理数是 1/3 #正确
我的第一个有理数是第二个有理数的 2/2.333333333333333 倍#incorrect
我应该得到的输出是:
我的第一个有理数是 2/7
它的立方体是 8/343
它的近似浮点值为0.2857142857142857
我的第二个有理数是 1/3
我的第一个有理数是第二个有理数的 6/7 倍
我尝试将 str() 和 int() 放在代码中某些变量的前面,但它说这些操作数不适用于“/”和“**”
当我从代码中删除浮点数时,我收到以下错误消息:
回溯(最近一次通话最后):
文件“/Users/******/Desktop/ration/rationaluse.py”,第 10 行,打印中(“我的第一个理性是”,r1/r2,“比第二个大”)
文件“/Users/*****/Desktop/ration/rational.py”,第 15 行,在truediv中 返回 Rational(self.numerator, self.denominator * (other)) TypeError: unsupported operand type(s) for * : '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")
解决方案
推荐阅读
- keycloak - is there an admin API for keycloak to get the OIDC installation JSON
- node.js - Angular 7 Universal(服务器端渲染)[错误参考错误:未定义文档]
- android - Types may only contain one @Inject constructor
- javascript - 单个图像的不同部分所需的不同悬停颜色
- angular - 如何订阅 Angular ControlValueAccessor 指令中的 FormControl 值更改
- r - Excel/R 中的矩阵操作
- python - Pandas 在同一数据框中使用多列映射 groupby
- reactjs - gulp serve 命令无法在 SPFX 上使用 react
- php - 使用单个查询从两个不同的 mysql 表中获取数据时遇到问题..!
- linux - 无需持续远程桌面连接即可运行 GUI