Python中计算Delta实现一元二次方程求根 代码运行错误求助
你的代码存在以下几个核心问题:
- 没有定义计算delta变量就直接调用,一元二次方程的判别式delta公式为 Δ = b² - 4ac,这是代码运行报错的核心原因
- x1、x2的计算时机错误:你把根的计算放在了delta计算之前,此时delta不存在自然无法运行;且delta小于0时无法进行开平方运算,根的计算必须放在delta值的判断分支内
- 输入提示文本、公式输出顺序、输出内容格式与任务要求不匹配,delta小于0时的输出内容也不符合要求
修正后的完整代码如下:
# 先输出要求的公式提示 print("Formula in the form: a*x**2 + b*x + c == 0") # 按要求获取用户输入 a = float(input("Specify an A:")) b = float(input("Specify B:")) c = float(input("Specify C:")) # 计算判别式delta delta = b ** 2 - 4 * a * c if delta > 0: x_1 = (-b - delta ** 0.5) / (2 * a) x_2 = (-b + delta ** 0.5) / (2 * a) print(f'''Square root of the quadratic equation or prime numbers of the quadratic equation: x_1 = {x_1} x_2 = {x_2}''') elif delta == 0: x = (-b) / (2 * a) print(f'''The primes of the quadratic equation/square root of the quadratic equation: x_1 = x_2 = {x}''') else: print("No solutions")
内容的提问来源于stack exchange,提问作者Davidcopperfield
相关产品推荐
相关产品推荐

