【題解】ZeroJudge a006: 一元二次方程式

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=a006
【解題想法】內建數學函數

  • sqrt( ) 回傳值額度資料型態為 double,但本題有實根的情況下,答案恰好都是整數解。
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    if (b * b - 4 * a * c == 0){
        int x = -b / (2 * a);
        cout << "Two same roots x=" << x << "\n";
    } else if (b * b - 4 * a * c > 0){
        int x = -b;
        int y = sqrt(b * b - 4 * a * c);
        cout << "Two different roots x1=" << (x + y) / (2 * a) << " , x2=" << (x - y) / (2 * a) << "\n";
    } else {
        cout << "No real root\n";
    }
    return 0;
}

Python code (credit: Amy Chou)

a, b, c = map(int, input().split())

if b**2 - 4*a*c == 0:
    x = int(-b / (2*a))
    print(f"Two same roots x={x}")
elif b**2 - 4*a*c > 0:
    x = -b / (2*a)
    y = (b**2 - 4*a*c) ** 0.5 / (2*a)
    x1 = int(x + y)
    x2 = int(x - y)
    print(f"Two different roots x1={x1} , x2={x2}")
else:
    print("No real root")
分享本文 Share with friends