-3

(在没有导入的二次方程中查找 x 的值。)每当我运行程序时,Python 都会停止discriminant = (b ** 2) - 4(a * c)并显示 TypeError: 'int' object is not callable。怎么了?

#------SquareRootDefinition---------#
def Square_Root(n, x):
if n > 0:
    y = (x + n/x) / 2
    while x != y:
        x = y
        return Square_Root(n, x)
    else:
        if abs(10 ** -7) > abs(n - x ** 2):
            return y
elif n == 0:
    return 0
else:
    return str(int(-n)) + "i"

#----------Quadratic Equation--------------#

a = input("Enter coefficient a: ")
while a == 0:
    print "a must not be equal to 0."
    a = input("Enter coefficient a: ")
b = input("Enter coefficient b: ")
c = input("Enter coefficient c: ")

def Quadratic(a, b, c):
    discriminant = (b ** 2) - 4(a * c)
    if discriminant < 0:
        print "imaginary"
    elif discriminant >= 0:
        Sqrt_Disc = Square_Root(discriminant)
        First_Root = (-b + Sqrt_Disc) / (2 * a)
        Second_Root = (-b - Sqrt_Disc) / (2 * a)

  return First_Root, Second_Root

X_1, X_2 = Quadratic(a, b, c)
4

3 回答 3

8

4(a * c)不是有效的 Python。你的意思是4 * a * c。您可以在数学符号中使用并列并省略乘法符号,但不能在 Python(或大多数其他编程语言)中使用。

于 2013-01-04T05:54:26.807 回答
5

您正在尝试4用作函数:

discriminant = (b ** 2) - 4(a * c)

你错过了*

discriminant = (b ** 2) - 4 * (a * c)

此外,如果您的判别式低于 0,您将得到一个未绑定的本地异常:

>>> X_1, X_2 = Quadratic(2, 1, 1)
imaginary
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in Quadratic
UnboundLocalError: local variable 'First_Root' referenced before assignment

您需要在此处添加一个return,或者更好的是,引发异常:

def Quadratic(a, b, c):
    discriminant = (b ** 2) - 4(a * c)
    if discriminant < 0:
        raise ValueError("imaginary")
    elif discriminant >= 0:
        Sqrt_Disc = Square_Root(discriminant)
        First_Root = (-b + Sqrt_Disc) / (2 * a)
        Second_Root = (-b - Sqrt_Disc) / (2 * a)

    return First_Root, Second_Root

您的Square_Root()函数缺少它的默认值x

def Square_Root(n, x=1):

通过这些更改,您的功能实际上可以工作:

>>> Quadratic(1, 3, -4)
(1, -4)
于 2013-01-04T05:54:36.103 回答
3

你需要做4 * (a * c)或者只是4 * a * c因为 python 认为你正在尝试调用一个函数4

于 2013-01-04T05:54:32.157 回答