1 import cmath
2 import math
3 import sys
4
5 def get_float(msg,allow_zero):
6 x =
None
7 while x
is None:
8 try:
9 x =
float(input(msg))
10 if not allow_zero
and abs(x) <
sys.float_info.epsilon:
11 print(
"zero is not allowed")
12 x =
None
13 except ValueError as err:
14 print(err)
15 return x
16
17 print(
"ax\N{SUPERSCRIPT TWO} +bx +c = 0")
18 a = get_float(
"enter a:", False)
19 b = get_float(
"enter b:", True)
20 c = get_float(
"enter c:", True)
21 x1 =
None
22 x2 =
None
23 discriminant = (b**2)-(4*a*
c)
24 if discriminant ==
0:
25 x1 = -(b/(2*
a))
26 else:
27 if discriminant >
0:
28 root =
math.sqrt(discriminant)
29 else:
30 root =
cmath.sqrt(discriminant)
31
32 x1 = (-b+root) / (2*
a)
33 x2 = (-b -root) /(2*
a)
34
35 equation = (
"{0}x\N{SUPERSCRIPT TWO}+{1}+{2} = 0""\N{RIGHTWARDS ARROW}X = {3}").format(a,b,c,x1)
36 if x2
is not None:
37 equation +=
" or x = {0}".format(x2)
38 print(equation)
转载于:https://www.cnblogs.com/LLWH134/p/8118945.html
相关资源:Python解一元二次方程