求一元二次方程的根,但是输入值后,实数部分显示的是-0,怎么让它显示0?
import mathk = input().split()
a = float(k)
b = float(k)
c = float(k)
h = h1 = h2 = h3 = 0
if b*b == 4 * a * c:
h = -b + math.sqrt(b*b-4*a*c)
h = h / (2*a)
print("x1=x2=%.5f"%h)
elif b*b > 4 * a * c:
h1 = -b + math.sqrt(b*b-4*a*c)
h1 = h1 / (2*a)
h2 = -b - math.sqrt(b*b-4*a*c)
h2 = h2 / (2*a)
print("x1=%.5f;x2=%.5f"%(h1,h2))
elif b*b < 4 * a * c:
h1 = -b / (2*a)
h2 = math.sqrt(4*a*c-b*b)
h2 = h2 / (2*a)
print("x1=%.5f+%.5fi;x2=%.5f-%.5fi"%(h1,h2,h1,h2))
#a,b,c是三个系数,h1,h2分别是两个解
输入1 0 7.3之后,实数部分显示的是-0.00000,怎么变成0.00000呢?
本帖最后由 临时号 于 2022-6-17 01:58 编辑
判断实数部分的值是否为0,如果是,则不考虑实数部分的符号
import math
k = input().split()
a = float(k)
b = float(k)
c = float(k)
h = h1 = h2 = h3 = 0
if b*b == 4 * a * c:
h = -b + math.sqrt(b*b-4*a*c)
h = h / (2*a)
if h == 0:
h = abs(h)
print("x1=x2=%.5f"%h)
elif b*b > 4 * a * c:
h1 = -b + math.sqrt(b*b-4*a*c)
h1 = h1 / (2*a)
h2 = -b - math.sqrt(b*b-4*a*c)
h2 = h2 / (2*a)
if h1 == 0:
h1 = abs(h1)
if h2 == 0:
h2 = abs(h2)
print("x1=%.5f;x2=%.5f"%(h1,h2))
elif b*b < 4 * a * c:
h1 = -b / (2*a)
h2 = math.sqrt(4*a*c-b*b)
h2 = h2 / (2*a)
if h1 == 0:
h1 = abs(h1)
if h2 == 0:
h2 = abs(h2)
print("x1=%.5f+%.5fi;x2=%.5f-%.5fi"%(h1,h2,h1,h2))
兄弟,好奇问一下,为什么系数有小数?一元二次方程系数不是都是整数吗?ax^2 + bx + c = 0,系数:a、b、c 本帖最后由 傻眼貓咪 于 2022-6-17 09:41 编辑
class Equation:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def roots(self):
# 判别式 D
D = (self.b * self.b) - (4 * self.a * self.c)
if not D: # D = 0
return (- self.b) / (2 * self.a)
elif D < 0: # D < 0
real = (- self.b) / (2 * self.a)
imag = ((-D) ** .5) / (2 * self.a)
return ("%d+%di"%(real, imag), "%d-%di"%(real, imag))
else: # D > 0
x1 = (- self.b + (D ** .5)) / (2 * self.a)
x2 = (- self.b - (D ** .5)) / (2 * self.a)
return x1, x2
a, b, c = map(int, input().split()) # 三个系数
E = Equation(a, b, c)
print("根:", *E.roots())1 -3 10
根: 1+2i 1-2i
1 -3 -10
根: 5.0 -2.0
页:
[1]