首页 > 解决方案 > 我的 python 代码(二次方程求解器)不工作,任何原因/

问题描述

这是我的第二个 python 练习程序,我遇到了一个问题。正如标题所说,我想做一个二次方程求解器,但我遇到了一个问题。

在代码询问我关于 A、B 和 C 值的问题后,它并没有解决它,而是再次问我同样的问题。

这是代码:

import math

def quadratic_solver():

    print("Hello, this code allows the user to solve quadratic equations easily.")

    while True:
        a_value_raw = (input("Please enter the A value: "))
        b_value_raw = (input("Now type in the B value: "))
        c_value_raw = (input("And finally, type the C value: "))

        # This helps to turn user inputs to floats, or it might not help idk.
        a_value = float(a_value_raw)
        b_value = float(b_value_raw)
        c_value = float(c_value_raw)

        discriminant = pow(b_value, 2) - 4 * a_value * c_value

        if discriminant > 0:
            root_1 = str((-b_value + (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            root_2 = str((-b_value - (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            print("The equation has TWO real roots: ")
            print("Root 1 = " + root_1)
            print("Root 2 = " + root_2)
        else:
            continue

        if discriminant == 0:
            only_root = str((-b_value + (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            print("The equation has only ONE root: ")
            print(only_root)
        else:
            continue

        if discriminant < 0:
            print("The equation has NO real roots.")
        else:
            continue


quadratic_solver()

标签: pythonpython-3.x

解决方案


我认为你的意思是有一个if/elif/else链条:

        if discriminant > 0:
            root_1 = str((-b_value + (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            root_2 = str((-b_value - (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            print("The equation has TWO real roots: ")
            print("Root 1 = " + root_1)
            print("Root 2 = " + root_2)
        elif discriminant == 0:
            only_root = str((-b_value + (math.sqrt(pow(b_value, 2)) - 4 * a_value * c_value)) / 2 * a_value)
            print("The equation has only ONE root: ")
            print(only_root)
        else:
            print("The equation has NO real roots.")

推荐阅读