2012/02/12

[zerojudge] a006 一元二次方程式

題目:https://zerojudge.tw/ShowProblem?problemid=a006
說明:數學問題,代入公式求解,依題目要求印出結果。

Java 版
import java.util.Scanner;
import java.lang.Math;

public class A006 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String [] str = in.nextLine().split(" ");
            int a = Integer.parseInt(str[0]);
            int b = Integer.parseInt(str[1]);
            int c = Integer.parseInt(str[2]);
            double r = Math.pow(b, 2) - 4 * a * c;

            if(r < 0) {
                System.out.println("No real root");
            }
            else if(r == 0) {
                double x = 0.5 * -b / a;
                System.out.println("Two same roots x=" + (int)x);
            }
            else {
                double k = Math.sqrt(r);
                double x1 = 0.5 * (-b + k) / a;
                double x2 = x1 - k;
                System.out.println("Two different roots x1="+ (int)x1 
                        +" , x2=" + (int)x2);
            }
        }
    }
}
Python 版 (2022.07)
a, b, c = map(int, input().split(' '))
r = b * b - 4 * a * c
if r < 0:
    print('No real root')
elif r == 0:
    x = 0.5 * -b / a
    print('Two same roots x={}'.format(int(x)))
else:
    k = r ** 0.5
    x1 = 0.5 * (-b + k) / a
    x2 = x1 - k
    print('Two different roots x1={} , x2={}'.format(int(x1), int(x2)))

沒有留言:

張貼留言