본문 바로가기
Java 언어

Java로 이차방정식 풀기

by treeCoder 2021. 1. 30.

Java로 이차방정식 풀기이다.

//package practice_to_high;
import java.util.Scanner;

public class Quad {
    public static void main(String[] args) {

        double a,b,c, determinant, root, x1, x2;

        Scanner Sc =new Scanner(System.in);

        System.out.println("This program provides the roots of quadratic equation (ax^2+bx+c=0).");
        System.out.println("Enter a quadratic term coefficient (a).");         a = Sc.nextDouble();
        System.out.println("Enter a primary term coefficient (b).");           b = Sc.nextDouble();
        System.out.println("Enter a constant term (c).");                      c = Sc.nextDouble();

        determinant=(b * b) - ( 4 * a * c );
        root = Math.sqrt(determinant);

        // code to calculate roots
        if(determinant > 0) {
            x1 = (-b + root) / ( 2 * a );
            x2 = (-b - root) / (2 * a );
            System.out.print("The roots of the quadratic equation are " + x1 +" and " + x2 + ".");
        }
        if(determinant == 0) {
            x1=(-b + root)/(2*a);
            System.out.print("The roots are two real and equal roots which is "+x1+".");
        }
        if(determinant < 0) {
            // roots are complex number and distinct
            double real = -b / (2 * a);
            double imaginary = Math.sqrt(-determinant) / (2 * a);
            System.out.format("root1 = %.2f+%.2fi", real, imaginary);
            System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
        }
    }
}

 

다음은 실행화면이다.

 

댓글