You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二次方程求解代码故障求助:无法写入方程根至文件

二次方程求解代码问题排查与修复

代码中的核心问题

  • 赋值错误:get_coefficients函数里处理负号时,value == "-1"是比较而非赋值,应改为value = "-1",否则会因value为"-"无法转换为整数报错。
  • 常数项提取逻辑错误:调用get_coefficients(input_str, "")会匹配所有字符串,错误返回第一个项的系数,需改为筛选不含x的项来提取常数项c。
  • 缺失项未处理:若方程中某一项缺失(如无一次项),get_coefficients无返回值会触发TypeError,需添加默认返回0的逻辑。
  • 格式兼容性不足:无空格的方程(如2x^2+3x-5)无法被split()正确拆分,需先预处理字符串,将+、-转换为带空格的形式。
  • 复数根未处理:判别式小于0时直接返回"No roots",未考虑复数域的共轭复根。

修正后的完整代码

def read_equation(textfile: str) -> str:
    with open(textfile, 'r') as file:
        equation = file.read().strip()
    return equation

def get_coefficients(input_str: str, target: str) -> int:
    # 预处理:将符号转换为带空格的形式,确保每项独立
    processed = input_str.replace("+", " +").replace("-", " -")
    for term in processed.split():
        # 处理常数项的情况
        if target == "" and "x" not in term:
            try:
                return int(term)
            except ValueError as err:
                print(err)
                raise TypeError("常数项不是整数")
        # 处理含x的项
        elif term.endswith(target):
            try:
                value = term.replace(target, "", 1)
                if not value or value == "+":
                    value = "1"
                elif value == "-":
                    value = "-1"  # 修正赋值错误
                return int(value)
            except ValueError as err:
                print(err)
                raise TypeError(f"{target}项的系数不是整数")
    # 未找到对应项时返回0
    return 0

def get_a_b_c(input_str: str) -> tuple:
    a = get_coefficients(input_str, "x^2")
    b = get_coefficients(input_str, "x")
    c = get_coefficients(input_str, "")
    return a, b, c

def solve_quadratic_equation(a: int, b: int, c: int) -> str:
    if a == 0:
        return "这不是二次方程"
    d = b ** 2 - 4 * a * c
    if d > 0:
        x1 = (-b + d ** 0.5) / (2 * a)
        x2 = (-b - d ** 0.5) / (2 * a)
        roots = f"x1 = {x1:.2f}\nx2 = {x2:.2f}"
    elif d == 0:
        x = -b / (2 * a)
        roots = f"x = {x:.2f}"
    else:
        # 处理复数根
        real_part = -b / (2 * a)
        imag_part = (-d) ** 0.5 / (2 * a)
        roots = f"x1 = {real_part:.2f} + {imag_part:.2f}i\nx2 = {real_part:.2f} - {imag_part:.2f}i"
    return roots

def write_roots(output: str, textfile: str) -> None:
    with open(textfile, 'a') as file:
        file.write('\n--- 方程的根 ---\n')
        file.write(output)

def main():
    try:
        user_input = read_equation(textfile="equation.txt")
        coefficients = get_a_b_c(user_input)
        roots = solve_quadratic_equation(*coefficients)
        write_roots(output=roots, textfile="equation.txt")
    except Exception as e:
        print(f"运行出错:{e}")

if __name__ == "__main__":
    main()

额外说明

  • 新增了对非二次方程的判断(a=0时提示)
  • 根的结果保留两位小数,可读性更强
  • 写入文件时添加分隔线,区分原方程和结果
  • 新增异常捕获,方便定位运行时错误

内容的提问来源于stack exchange,提问作者la_felice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:54:54