需要帮助在python中设置二次方程

时间:2016-02-24 22:48:54

标签: python equation quadratic

(这是我运行它时应该出现的方式。)     a = 3; b = 5; c = 4     没有解决方案

到目前为止,我已经在python中设置了这个,但我不知道我做错了什么。 (注意:我的教授希望我们在定义函数的末尾调用main)

import math
import sys
def main():
    print("a = ",a,";b = ",b,";c = ",c,)
    print_quadratic_solution(3, 5, 2)
    a = print_quadratic_solution(a)
    b = print_quadratic_solution(b)
    c = print_quadratic_solution(c)

def print_quadratic_solution(a, b, c):
    a = int(a)
    b = int(b)
    c = int(c)
    discriminant = b**2 - 4*a*c

    if discriminant < 0:
        print("There are no solutions.")
    elif discriminant == 0:
        x = (-b + math.sqrt(discriminant)) / (2*a)
        print("There is a double root at", x)
    elif discriminant > 0:
        x1 = (-b + math.sqrt(discriminant)) / (2*a)
        x2 = (-b - math.sqrt(discriminant)) / (2*a)
        print("The first root is", x1, " and the second is", x2, ".")

main()

结果如下:

The first root is -0.6666666666666666  and the second is -1.0 .
Traceback (most recent call last):
  File "C:\Users\Juan1\Documents\Computer Science 1300\EliAssignment6.py", line 23, in <module>
    main()
  File "C:\Users\Juan1\Documents\Computer Science 1300\EliAssignment6.py", line 5, in main
    print("a = ",a,";b = ",b,";c = ",c,)
NameError: name 'a' is not defined

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

错误NameError: name 'a' is not defined意味着它的含义。变量a在分配之前没有任何值。所以你不能把它放在print声明中。

答案 1 :(得分:0)

这是一个很好的家庭作业,我认为这个练习应该教你如何破译错误信息。我不会马上把你出错的地方放弃。但是,我会为您提供错误消息的解释。

 The first root is -0.6666666666666666  and the second is -1.0 .
Traceback (most recent call last):
  File "C:\Users\Juan1\Documents\Computer Science 1300\ElizabethZamudioAssignment6.py", line 23, in <module>
    main()
  File "C:\Users\Juan1\Documents\Computer Science 1300\ElizabethZamudioAssignment6.py", line 5, in main
    print("a = ",a,";b = ",b,";c = ",c,)
NameError: name 'a' is not defined

以下

NameError : name 'a' is not defined

代码变量a中的某个位置在被赋值之前被访问/使用。因此,在执行时,您的计算机不知道a是什么。

现在,这个执行点在哪里? 要知道这一点,你应该深入了解行号。 这就是 Traceback

Traceback (most recent call last):
  File "C:\Users\Juan1\Documents\Computer Science 1300\ElizabethZamudioAssignment6.py", line 23, in <module>
    main()
  File "C:\Users\Juan1\Documents\Computer Science 1300\ElizabethZamudioAssignment6.py", line 5, in main
    print("a = ",a,";b = ",b,";c = ",c,)

根据您的追溯,您的计算机尝试运行main()功能。此函数调用是在line number 23的{​​{1}}

中进行的

在同一文件的File "C:\Users\Juan1\Documents\Computer Science 1300\ElizabethZamudioAssignment6.py"函数中,main有一个line 5

现在,您是否看到自己在第5行之前的NameError函数中分配/启动变量a。因此,您的错误消息正在尝试告诉您启动该值。您的计算机在第5行不知道main()是什么。

希望这会有所帮助。