Python 基础知识简单

求二次方程的根

“求二次方程的根”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 find_roots(a, b, c),它采用三个数字 abc 表示二次方程 ax² + bx + c = 0 的系数,并返回根。

使用二次公式:x = (-b ± √(b²-4ac)) / (2a)

返回:

- 当 b²-4ac >= 0 (root1 <= root2) 时,两个浮点数 (root1, root2) 的元组四舍五入到小数点后两位

- 当 b²-4ac < 0 时,字符串“复数根”(判别式为负)

假设 a ≠ 0。

约束条件
  • -1000 <= a, b, c <= 1000
  • a != 0

示例

Example 1
Input
find_roots(1, -3, 2)
Output
(1.0, 2.0)
Explanation

x² - 3x + 2 = 0. Discriminant = 9 - 8 = 1. Roots: (3±1)/2 = 2 and 1. Sorted: (1.0, 2.0).

Example 2
Input
find_roots(1, -2, 1)
Output
(1.0, 1.0)
Explanation

x² - 2x + 1 = 0. Discriminant = 4 - 4 = 0. Double root: x = 2/2 = 1.0.

Example 3
Input
find_roots(1, 1, 1)
Output
'Complex Roots'
Explanation

x² + x + 1 = 0. Discriminant = 1 - 4 = -3 < 0. No real roots.

Need a Hint?
考虑使用特定于数字的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。