[英]quadratic eqn solver only solve for quadratic equation with variable x
x = input(" write a quadratic equation ")
x=(x.replace(" ",""))
我寫這個是為了從輸入中刪除所有空格,以便索引變得容易
q = x.find("x")
w=int(q+1)
代碼運行良好,但代碼中的索引取決於 x 的索引 如果有人用不同的變量編寫了一個方程,則無法工作,那么 x 下面是整個代碼
x = input(" write a quadratic equation ")
print ("")
x=(x.replace(" ",""))
q = x.find("x")
w=int(q+1)
abc = x[0:q+1]
bcd = x[w+1:]
if (x[w]!="^") :
y=abc + "^2" +bcd
y=(y.replace(" ",""))
print(y)
else:
print(x,end ="""
""")
A = int(x[:w-1])
e=x.rfind("x")
B=int(x[w+1:e])
C=int(x[e+1:])
r=(((-B) - ((B*B)-(4*A*C))**(1/2))/ ((2*A)))
t=(((-B) + ((B*B)-(4*A*C))**(1/2))/((2*A)))
print( "the roots are " ,r,"and" ,t)
如何使代碼適用於所有字母 有什么方法可以將輸入中的字母更改為 1letters iex
我建議檢查'abcdefghijklmnopqrstuvwxyz'
每個字符,並調用x.find(character)
。 如果返回-1
,則該字符不存在。 重復迭代直到找到一個字符並假設這個字符是要求解的變量。
equation = input("Write a quadratic equation: ")
print("")
equation = equation.replace(" ","")
alphabet = 'abcdefghijklmnopqrstuvwxyz'
index = -1
i = 0
while index == -1:
index = equation.find(alphabet[i])
i += 1
letter = equation[index]
# continue rest of program from here, assuming letter variable is the character to solve for
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.