• 发表于 6个月前
• 阅读 1
• 收藏 0
• 评论 0
``````"""

①把方程化成一般形式ax²+bx+c=0(a≠0)，确定a，b，c的值（注意符号）；
②求出判别式△=b²-4ac的值，判断根的情况；
③在△>=0注：此处△读“德尔塔”）的前提下，把a、b、c的值代入公式进行计算，求出方程的根。
"""
import cmath
import math
import sys

def get_float(msg, allow_zero):
x = None
while x is None:
try:
x = float(input(msg))
if not allow_zero and abs(x) < sys.float_info.epsilon:
print('zero is not allowed')
x = None
except ValueError as err:
print(err)
return x

print('ax\N{SUPERSCRIPT TWO} + bx + c = 0')
a = get_float('enter a: ', False)
b = get_float('enter b: ', True)
c = get_float('enter c:', True)
x1 = None
x2 = None
discriminant = (b**2) - (4*a*c)
if discriminant == 0:
x1 = -(b/(2*a))
else:
if discriminant > 0:
root = math.sqrt(discriminant)
else:
root = cmath.sqrt(discriminant)
x1 = (-b + root) / (2*a)
x2 = (-b - root) / (2*a)
# equation = '{0}x\N{SUPERSCRIPT TWO} + {1}X + {2} = 0 \N{RIGHTWARDS ARROW} x = {3}'.format(a, b, c, x1)
equation = '{a}x\N{SUPERSCRIPT TWO} + {b}X + {c} = 0 \N{RIGHTWARDS ARROW} x = {x1}'.format(**locals())
if x2 is not None:
equation += ' or x = {0}'.format(x2)
print(equation)

``````

``````ax² + bx + c = 0
enter a: 2
enter b: 3
enter c:4
2.0x² + 3.0X + 4.0 = 0 → x = (-0.75+1.1989578808281798j) or x = (-0.75-1.1989578808281798j)

``````

×