二次公式计算器

时间:2021-03-17 13:20:42

标签: python-3.x

有人能帮我找出我今天早上写的这个非常基本的代码哪里出了问题吗?试图为 Python 3 上的二次公式问题编写一个计算器,但我收到一条错误消息:“NameError: name 'sqrt' is not defined”。这有点道理,但后来我不知道如何把平方根放在那里。我应该使用其他功能吗?

PS:我在 YouTube 和电子书之外自己学习。所以,如果你能像我五岁那样向我解释,那就太棒了,谢谢。我几天前才开始学习。


    # Quadratic Formula Calculator
    # What could possibly go wrong?
    
    # Define a, b, and c variables for the quad formula
    a = int(input("What is your 'a' variable? "))
    b = int(input("What is your 'b' variable? "))
    c = int(input("What is your 'c' variable? "))
    
    print(f"""
    Your quadratic formula result in + is...
    {((-b) + ((sqrt(b) ** 2) - (4 * a * c))) / (2 * a)}
    """)
    
    print(f"""
    Your quadratic formula result in - is...
    {((-b) - ((sqrt(b) ** 2) - (4 * a * c))) / (2 * a)}
    """)

2 个答案:

答案 0 :(得分:2)

sqrt 不是 python 的内置函数。它是 math 模块的一个函数。所以你必须先导入数学。

代码必须是:

    import math
    a = int(input("What is your 'a' variable? "))
    b = int(input("What is your 'b' variable? "))
    c = int(input("What is your 'c' variable? "))
        
    print(f"""
    Your quadratic formula result in + is...
    {((-b) +  (math.sqrt(b ** 2 - 4 * a * c))) / (2 * a)}
     """)
        
    print(f"""
    Your quadratic formula result in - is...
    {((-b) - (math.sqrt(b ** 2 - 4 * a * c))) / (2 * a)}
    """)

答案 1 :(得分:1)

您需要这样加载 sqrt 函数:

import math

然后像这样使用你的平方根:

math.sqrt(9)

返回 3。

相关问题