试图创建一个Python程序来找到一个平方根

2024-09-30 14:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我写这段代码是为了计算一个二次函数的根,当给定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'

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


Tags: andtheforinputreturnifthatis
3条回答

你不能用字符串做数学。正如A.Lorefice所说,在输入前面加int将把给定的字符串变成整数。你知道吗

这里的问题是input将类型化的输入作为字符串类型。检查它是否工作:

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(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

相关问题 更多 >