Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

quadratic formula using python

Trying to create a program that takes in three arguments that represent the a, b, and c values in the quadratic formula. The values should be to two decimal places. You do not need to account for imaginary values. Then print out both roots in the form:

The solutions are x and y

Where x and y correspond to the positive and negative roots, respectively.

Having issues with my code:

import math

a = float(input('please input a number:'))
b = float(input('please input a number3:'))
c = float(input('please input a number2:'))
d = (b**2) - (4*a*c)

sol1 = str(round((-b-cmath.sqrt(d))/(2*a),2))
sol2 = str(round((-b+cmath.sqrt(d))/(2*a),2))

print('The solution are {1.real:.2f} and {0.real:.2f}'.format(sol1,sol2))
question from:https://stackoverflow.com/questions/65929638/quadratic-formula-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your code you imported math but used cmath. But, a simpler solution would be to not import anything and use the built in power function. Also, python handles printing integers, floats, and complex numbers by itself, so you don't need to worry about casting.

Try this:

# Get inputs
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

# Calculate discriminant
discriminant = b**2 - 4*a*c

# Get solutions, x^0.5 = square root
x1 = (-b + discriminant**0.5) / (2*a)
x2 = (-b - discriminant**0.5) / (2*a)

# Output
print(f"Solutions: {x1} and {x2}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...