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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。