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

Python二次方程求解结果保留4位浮点数问题

解决Python复数结果保留4位小数的问题

你的错误在于混淆了两种字符串格式化语法:%运算符和str.format()方法不能混用,同时代码末尾还缺少闭合括号。以下是几种正确的实现方式:

方法1:使用str.format()格式化复数

直接在占位符中指定小数位数格式:.4f,Python支持对复数直接应用浮点数格式化规则,会自动处理实部和虚部:

import cmath

a = 1
b = -4
c = 1
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print("The solutions are {0:.4f} and {1:.4f}".format(sol1, sol2))

输出:

The solutions are 0.2679+0.0000j and 3.7321+0.0000j

方法2:使用f-string(Python3.6+推荐)

f-string语法更简洁直观,同样支持复数格式化:

import cmath

a = 1
b = -4
c = 1
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print(f"The solutions are {sol1:.4f} and {sol2:.4f}")

输出与方法1一致。

方法3:手动提取实部和虚部格式化

如果需要更精细的控制(比如虚部为0时隐藏),可以提取复数的real和imag属性单独格式化:

import cmath

a = 1
b = -4
c = 1
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

# 处理虚部为0的情况
def format_complex(num):
    if num.imag == 0:
        return f"{num.real:.4f}"
    else:
        return f"{num.real:.4f}+{num.imag:.4f}j"

print(f"The solutions are {format_complex(sol1)} and {format_complex(sol2)}")

输出:

The solutions are 0.2679 and 3.7321

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:11:06