对于我们的家庭作业,我们被要求计算二次方程,然后以ax^2 + bx + c = 0
的格式打印出来。
我们有以下打印条件:
我几乎让它工作,但遇到了一些小问题。
QuadraticEquation(a=-1,b=1,c=1)
QuadraticEquation(a=2,b=-3,c=-1)
QuadraticEquation(a=1,b=0,c=25)
QuadraticEquation(a=1.2,b=2.3,c=5.6)
QuadraticEquation(a=9.0,b=-1,c=81.0)
以上函数应返回为:
-x^2 + x + 1.0 = 0
2.0x^2 – 3.0x – 1.0 = 0
x^2 – 25.0 = 0
1.2x^2 + 2.3x + 5.6 = 0
9.0x^2 - x + 81.0 = 0
然而,我的回报是:
-x^2 + x + 1.0 = 0
2.0x^2 - 3.0x - 1.0 = 0
x^2 + 25.0 = 0
1.2x^2 + 2.3x + 5.6 = 0
9.0x^2 - 1.0x + 81.0 = 0
有谁看到我搞砸了?
from math import sqrt
class QuadraticEquation(object):
def __init__(self, a, b, c):
self.__a = float(a)
if self.__a == 0.0:
raise ValueError("Coefficient 'a' cannot be 0 in a quadratic equation.")
self.__b = float(b)
self.__c = float(c)
@property
def a(self):
return self.__a
@property
def b(self):
return self.__b
@property
def c(self):
return self.__c
def __str__(self):
a = self.__a
b = self.__b
c = self.__c
# a
if a < 0:
a = '-x^2'
elif a == 1:
a = 'x^2'
else:
a = '%sx^2' % a
# b
if b < 0:
b = ' - %sx' % (b * -1)
elif b == 0:
b = ''
elif b == 1:
b = ' + x'
else:
b = ' + %sx' % b
# c
if c < 0:
c = ' - %s' % (c * -1)
elif c == 0:
c = ''
else:
c = ' + %s' % c
return a + b + c + ' = 0'
if __name__ == '__main__':
equation1 = QuadraticEquation(a=-1,b=1,c=1)
equation2 = QuadraticEquation(a=2,b=-3,c=-1)
equation3 = QuadraticEquation(a=1,b=0,c=25)
equation4 = QuadraticEquation(a=1.2,b=2.3,c=5.6)
equation5 = QuadraticEquation(a=9.0,b=-1,c=81.0)
print(equation1) # -x^2 + x + 1.0 = 0
print(equation2) # 2.0x^2 – 3.0x – 1.0 = 0
print(equation3) # x^2 – 25.0 = 0
print(equation4) # 1.2x^2 + 2.3x + 5.6 = 0
print(equation5) # 9.0x^2 - x + 81.0 = 0
答案 0 :(得分:2)
所以你输出的问题&#34; - 1.0x&#34;而不是&#34; - x&#34;? 你应该纠正这个部分。您当前的代码适用于b = + 1,但不适用于b = -1,因为这种情况是在&#34; b&lt; 0&#34;条件。
我认为更好的解决方案是为输出使用新变量。试试这个:
# a
a_out = ''
if a != 0:
if a < 0:
a_out += '-'
if abs(b) != 1:
a_out += '%.1fx^2' % abs(a)
else:
a_out += 'x^2'
# b
b_out = ''
if b != 0:
if b < 0:
b_out += ' - '
else:
b_out += ' + '
if abs(b) != 1:
b_out += '%.1fx' % abs(b)
else:
b_out += 'x'
# c
c_out = ''
if c != 0:
if c < 0:
c_out = ' - %.1f' % (-c)
else:
c_out = ' + %.1f' % c
return a_out + b_out + c_out + ' = 0'
答案 1 :(得分:1)
夫妻问题,由于它的作业我不会给你答案,但指出了问题:)
# a
if a < 0:
a = '-x^2'
elif a == 1:
a = 'x^2'
else:
a = '%sx^2' % a
此处,如果a
任何负数,则第一个表达式为-x^2
。这意味着即使你有一个= -20,结果也会是-x^2
。
这里有三种情况,a是负数,a是1,否则。但实际上有4种情况:a是负数,不等于-1,a是负数,等于-1,a是正数,等于1,或者a是正数。