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)
如何使代码适用于所有字母 有什么办法可以将输入中的字母更改为1字母,即x
答案 0 :(得分:1)
我建议检查'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