寫一個 Python 程序,用一個例子找到一個二次方程的根。二次方程的數學表示是 ax +bx+c = 0。一個二次方程可以有兩個根,它們完全取決於判別式。如果判別式> 0,則該方程存在兩個不同的實根
如果判別式= 0,則存在兩個相等的實根。
而如果判別< 0, Two Distinct Complex Roots exists.
用 elif 求二次方程根的 Python 程序
這個 python 程序允許用戶輸入 a、b 和 c 的三個值。通過使用這些值,這個 Python 代碼使用 Elif 語句找到一個二次方程的根。
# Python Program to find roots of a Quadratic Equation
import math
a = int(input("Please Enter a Value of a Quadratic Equation : "))
b = int(input("Please Enter b Value of a Quadratic Equation : "))
c = int(input("Please Enter c Value of a Quadratic Equation : "))
discriminant = (b * b) - (4 * a * c)
if(discriminant > 0):
root1 = (-b + math.sqrt(discriminant) / (2 * a))
root2 = (-b - math.sqrt(discriminant) / (2 * a))
print("Two Distinct Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant == 0):
root1 = root2 = -b / (2 * a)
print("Two Equal and Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant < 0):
root1 = root2 = -b / (2 * a)
imaginary = math.sqrt(-discriminant) / (2 * a)
print("Two Distinct Complex Roots Exists: root1 = %.2f+%.2f and root2 = %.2f-%.2f" %(root1, imaginary, root2, imaginary))
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/129409.html