python - 我的 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()
解决方案
我认为你的意思是有一个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.")
推荐阅读
- sql-server - 访问权限 sp_configure 和 reconfigure 语句?
- google-apps-script - 在 Apps 脚本中为公司范围的插件配置可安装触发器
- sql - 在 Micosoft SQL Sever 2018 中将表达式转换为数据类型 int 的算术溢出错误
- csv - 需要在 Tableau 中加入表格
- angular - 在角度中找不到名称的控件
- python - 新顶层打开时 Tkinter 图像标签消失
- laravel - 从 laravel 降级嘲弄
- python - 随机播放句子 pytelegrambotapi python
- python - Django - 如何获取用户文件路径?
- ios - 从自定义框架访问情节提要不起作用