分数代码无法计算具有相同值的分数的差异
Fractions code not able to calculate difference for fractions with same values
我创建了一个包含 +、-、*、/ 的分数计算器。除了两个值相等的减法条件外,我的所有函数都可以正常工作。我相信这与我添加的 simplify(gcd) 函数有关,但不确定问题出在哪里。下面是我只保留了用于确定问题优先级的减法函数的代码:
Class Fraction:
def __init__(self, num, denom) -> None:
self.num = int(num / simplify(abs(num), abs(denom)))
self.denom = int(denom / simplify(abs(num), abs(denom)))
if self.denom < 0:
self.denom = abs(self.denom)
self.num = -1*self.num
elif self.denom == 0:
raise ZeroDivisionError("cansnot divide by zero")
def __sub__(self, other: "Fraction") -> "Fraction":
n: int = self.num * other.denom - self.denom * other.num
d: int = self.denom * other.denom
new = Fraction(n, d)
return (new)
def __str__(self) -> str:
if self.denom == 1:
return str(self.num)
else:
return(f"{self.num}/{self.denom}")
def simplify(num, denom):
while num != denom:
if num > denom:
num = num - denom
else:
denom = denom - num
return num
def get_fraction() -> Fraction:
"""Convert numerator and denominator to integer values"""
while True:
num: str = input("Enter the numerator")
denom: str = input("Enter the denominator")
try:
a = int(num)
b = int(denom)
return Fraction(a, b)
except ValueError:
print("Enter valid numerator and denominator")
def compute(f1: Fraction, operator: str, f2: Fraction) -> None:
okay = True
if operator == '-':
result = f1.__sub__(f2)
else:
print(operator, " is an unrecognized operator")
okay = False
if okay == True:
print(f"{f1} {operator} {f2} = {result}")
def main() -> None:
"""Main menu"""
print("Welcome to the Fraction Calculator! ")
while True:
print('Press Q to quit or any other key to start')
z = input("Start or Quit?")
if z == 'Q' or z == 'q':
exit()
else:
f1: Fraction = get_fraction()
operator: str = input("Operation (+, -, *, / , = , < , > , <= , >= , != ): ")
f2: Fraction = get_fraction()
try:
compute(f1, operator, f2)
except ZeroDivisionError as e:
print(e)
if __name__ == '__main__':
main()
下面是此代码的输出,其中两个分数都是 4/5,它只是给我一个空白输出。
Welcome to the Fraction Calculator!
Press Q to quit or any other key to start
Start or Quit? s
Enter the numerator 4
Enter the denominator 5
Operation (+, -, *, / , = , < , > , <= , >= , != ): -
Enter the numerator 4
Enter the denominator 5
所有其他值都适用于子函数,除非值相等。
您的简化方法是 gcd 的较慢版本,当 num 为零时将陷入无限循环。
您可以将其替换为:
from math import gcd
def simplify(num, denom):
return gcd(num,denom) if denom else 1
如果您不想导入数学,您可以使用比您当前在 simplify 中使用的减法形式更快的算法编写您自己的 gcd() 函数版本:
def gcd(a,b):
while b != 0: a,b = b,a%b
return abs(a)
或者,您可以将 simplify() 的代码替换为两个组件的实际简化,一步将标志置于顶部:
def simplify(num, denom):
g = gcd(num,denom) if denom else 1
s = -1 if (num<0) != (denom<0) else 1
return int(abs(num) // g * s), int(abs(denom) // g)
并在构造函数中像这样使用它:
self.num,self.denom = simplify(num,denom)
如果您使用 Decimal()(来自 decimal 模块)而不是 int() 转换字符串输入,这个改进的 simplify() 可以做更酷的事情,例如弄清楚:
simplify(-8.5,12.5) # is (-17, 25)
例如:
from decimal import Decimal
f = input("enter a fraction as a/b or a decimal value: ")
num,denom,*_ = map(Decimal,(*f.split("/"),1))
print(simplify(num,denom))
enter a fraction as a/b or a decimal value: 0.68
(17, 25)
我创建了一个包含 +、-、*、/ 的分数计算器。除了两个值相等的减法条件外,我的所有函数都可以正常工作。我相信这与我添加的 simplify(gcd) 函数有关,但不确定问题出在哪里。下面是我只保留了用于确定问题优先级的减法函数的代码:
Class Fraction:
def __init__(self, num, denom) -> None:
self.num = int(num / simplify(abs(num), abs(denom)))
self.denom = int(denom / simplify(abs(num), abs(denom)))
if self.denom < 0:
self.denom = abs(self.denom)
self.num = -1*self.num
elif self.denom == 0:
raise ZeroDivisionError("cansnot divide by zero")
def __sub__(self, other: "Fraction") -> "Fraction":
n: int = self.num * other.denom - self.denom * other.num
d: int = self.denom * other.denom
new = Fraction(n, d)
return (new)
def __str__(self) -> str:
if self.denom == 1:
return str(self.num)
else:
return(f"{self.num}/{self.denom}")
def simplify(num, denom):
while num != denom:
if num > denom:
num = num - denom
else:
denom = denom - num
return num
def get_fraction() -> Fraction:
"""Convert numerator and denominator to integer values"""
while True:
num: str = input("Enter the numerator")
denom: str = input("Enter the denominator")
try:
a = int(num)
b = int(denom)
return Fraction(a, b)
except ValueError:
print("Enter valid numerator and denominator")
def compute(f1: Fraction, operator: str, f2: Fraction) -> None:
okay = True
if operator == '-':
result = f1.__sub__(f2)
else:
print(operator, " is an unrecognized operator")
okay = False
if okay == True:
print(f"{f1} {operator} {f2} = {result}")
def main() -> None:
"""Main menu"""
print("Welcome to the Fraction Calculator! ")
while True:
print('Press Q to quit or any other key to start')
z = input("Start or Quit?")
if z == 'Q' or z == 'q':
exit()
else:
f1: Fraction = get_fraction()
operator: str = input("Operation (+, -, *, / , = , < , > , <= , >= , != ): ")
f2: Fraction = get_fraction()
try:
compute(f1, operator, f2)
except ZeroDivisionError as e:
print(e)
if __name__ == '__main__':
main()
下面是此代码的输出,其中两个分数都是 4/5,它只是给我一个空白输出。
Welcome to the Fraction Calculator!
Press Q to quit or any other key to start
Start or Quit? s
Enter the numerator 4
Enter the denominator 5
Operation (+, -, *, / , = , < , > , <= , >= , != ): -
Enter the numerator 4
Enter the denominator 5
所有其他值都适用于子函数,除非值相等。
您的简化方法是 gcd 的较慢版本,当 num 为零时将陷入无限循环。
您可以将其替换为:
from math import gcd
def simplify(num, denom):
return gcd(num,denom) if denom else 1
如果您不想导入数学,您可以使用比您当前在 simplify 中使用的减法形式更快的算法编写您自己的 gcd() 函数版本:
def gcd(a,b):
while b != 0: a,b = b,a%b
return abs(a)
或者,您可以将 simplify() 的代码替换为两个组件的实际简化,一步将标志置于顶部:
def simplify(num, denom):
g = gcd(num,denom) if denom else 1
s = -1 if (num<0) != (denom<0) else 1
return int(abs(num) // g * s), int(abs(denom) // g)
并在构造函数中像这样使用它:
self.num,self.denom = simplify(num,denom)
如果您使用 Decimal()(来自 decimal 模块)而不是 int() 转换字符串输入,这个改进的 simplify() 可以做更酷的事情,例如弄清楚:
simplify(-8.5,12.5) # is (-17, 25)
例如:
from decimal import Decimal
f = input("enter a fraction as a/b or a decimal value: ")
num,denom,*_ = map(Decimal,(*f.split("/"),1))
print(simplify(num,denom))
enter a fraction as a/b or a decimal value: 0.68
(17, 25)