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

如何将程序输出按照c0 + c1x + c2x²的多项式格式打印?

多项式格式打印实现方案

以下是适配任意长度系数列表的通用实现,可直接套用:


最简实现(直接输出c0 + c1*x^1 + c2*x^2格式)

如果你不需要优化书写格式,直接按要求的原始格式输出,可以用以下代码:

# 先提取所有系数并保留6位小数
coeffs = [round(finalresult[i][len(finalresult)], 6) for i in range(len(finalresult))]
# 按格式拼接所有项
output_str = " + ".join([f"{c}*x^{index}" for index, c in enumerate(coeffs)])
print(output_str)

优化版实现(符合常规数学书写习惯)

如果需要输出更符合日常使用的多项式格式(比如省略系数1、省略1次项的^1、跳过0系数项、自动处理正负号),可以用以下代码:

coeffs = [round(finalresult[i][len(finalresult)], 6) for i in range(len(finalresult))]
terms = []
for power, c in enumerate(coeffs):
    # 浮点数精度判断,跳过接近0的无效项
    if abs(c) < 1e-9:
        continue
    # 处理符号
    sign = "+" if c > 0 else "-"
    abs_c = abs(c)
    # 常数项(x^0)处理
    if power == 0:
        terms.append(f"{sign} {abs_c}")
        continue
    # 非0次项系数处理:系数为1时省略数字
    coeff_part = "" if abs(abs_c - 1) < 1e-9 else f"{abs_c}"
    # 次数处理:1次项省略^1
    power_part = "x" if power == 1 else f"x^{power}"
    terms.append(f"{sign} {coeff_part}{power_part}")

# 处理全零系数的特殊情况
if not terms:
    poly_str = "0"
else:
    # 去掉首项多余的+号
    poly_str = " ".join(terms).lstrip("+ ").strip()
print(poly_str)

效果示例

如果系数列表为[2, -1, 3, 0, -2],输出结果为:2 - x + 3x^2 - 2x^4


内容的提问来源于stack exchange,提问作者KIRAN THYLOOR SHIVU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:48:02