试图创建一个Python程序来查找二次曲线的根
我写这段代码是为了计算二次函数的根,当给定a、b和c的值时,其形式为ax^2+bx+c=0:试图创建一个Python程序来查找二次曲线的根,python,math,ide,typeerror,Python,Math,Ide,Typeerror,我写这段代码是为了计算二次函数的根,当给定a、b和c的值时,其形式为ax^2+bx+c=0: a = input("a") b = input("b") c = input("c") print("Such that ", a, "x^2+", b, "x+", c, "=0,") def greaterzero(a, b, c): x = (((b**2 - (4*a*c))**1/2) -b)/2*a return x def smallerzero(a, b, c):
a = input("a")
b = input("b")
c = input("c")
print("Such that ", a, "x^2+", b, "x+", c, "=0,")
def greaterzero(a, b, c):
x = (((b**2 - (4*a*c))**1/2) -b)/2*a
return x
def smallerzero(a, b, c):
x = (-1*((b**2 - (4*a*c))**1/2) -b)/2*a
return x
if smallerzero(a, b, c) == greaterzero(a, b, c):
print("There is only one zero for the quadratic given a, b, and c: ",
greaterzero(a, b, c))
else:
print ("The greater zero for the quadratic is ", greaterzero(a, b, c))
print ("The smaller zero for the quadratic is ", smallerzero(a, b, c))
当我执行程序(在交互模式下)并分别为a、b和c输入1、2和1时,这是输出:
a1
b2
c1
Such that 1 x^2+ 2 x+ 1 =0,
Traceback (most recent call last):
File "jdoodle.py", line 13, in <module>
if smallerzero(a, b, c) == greaterzero(a, b, c):
File "jdoodle.py", line 11, in smallerzero
x = (-1*((b**2 - (4*a*c))**1/2) -b)/2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
a1
b2
c1
使得1x^2+2x+1=0,
回溯(最近一次呼叫最后一次):
文件“jdoodle.py”,第13行,在
如果较小的零(a,b,c)=较大的零(a,b,c):
文件“jdoodle.py”,第11行,在smallerzero中
x=(-1*((b**2-(4*a*c))**1/2)-b)/2
TypeError:不支持**或pow()的操作数类型:'str'和'int'
这里有什么问题?
我还没有正式学习如何使用交互模式。我想要一个简单的解释/介绍,或者一个网站/教程来提供。这里的问题是输入将输入类型作为字符串类型。检查这是否可以工作:
a = int(input("Type the value of a: "))
b = int(input("Type the value of b: "))
c = int(input("Type the value of c: "))
在这里,您将显式地将输入类型从str更改为integer,以便可以通过算术运算处理变量。您忘记将输入值转换为数字类型
a=int(输入('a'))
或a=float(输入('a'))
或者更干净一点:
def input_num(prompt):
while True:
try:
return int(input(prompt + ': '))
except ValueError:
print('Please input a number')
a = input_num('a')
# ... etcetera
你不能用字符串做数学题。正如A.Lorefice所说,在输入前加int将把给定的字符串更改为整数。谢谢你的帮助!但我读到原始输入将其解释为字符串,而输入将其解释为整数。。。这是真的吗?如果是这样,为什么还需要指定它是一个int呢?不,这不是真的,仍然返回一个
字符串
:“然后函数从输入中读取一行,将其转换为一个字符串(去掉尾随的换行符),并返回该字符串。”@user10059620:这对Python 2来说有点正确,但对Python 3来说不是真的。到目前为止,这里的所有答案都假设您正在运行Python3,这是当前的标准版本,也是任何Python初学者都应该学习的。您正在运行哪个版本的Python?(解释为什么只有Python2才是正确的需要更多的时间。)@user10059620:那么你所阅读的内容对于你的情况是错误的,到目前为止,你可以使用这里的三个答案中的任何一个。我对robinsax的答案投了更高的票,但是你应该通过点击答案左上角的复选标记来接受对你帮助最大的答案。这就是你向回答者表示感谢的方式,也有助于其他人看到你的问题得到了回答。