试图创建一个Python程序来查找二次[重复]的根

问题描述 投票:-2回答:3

这个问题在这里已有答案:

我写这个代码来计算二次函数的根,当给出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):
    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'

这是什么问题?我还没有正式学习如何使用交互模式。我想要一个简单的解释/介绍或提供一个的网站/教程。

python math ide typeerror
3个回答
0
投票

这里的问题是输入将输入的输入作为字符串类型。检查这是否有效:

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更改为整数,以便您的变量可以通过算术运算来处理。


2
投票

您忘记将输入值强制转换为数字类型。

a = int(input('a'))a = float(input('a'))

或者,有点清洁:

def input_num(prompt):
    while True:
        try:
            return int(input(prompt + ': '))
        except ValueError:
            print('Please input a number')

a = input_num('a')
# ... etcetera

0
投票

你不能用字符串做数学。正如A.Lorefice所说,将int放在输入前会将给定的字符串更改为整数。

© www.soinside.com 2019 - 2024. All rights reserved.