이 글에서는 자바(Java)를 활용해 이차방정식의 근을 구하는 방법을 단계별로 살펴봅니다. 이차방정식은 최고 차수가 2인 대수 방정식으로, 계수 값에 따라 해가 실수일 수도 있고 허수(복소수)일 수도 있다는 특징이 있습니다.
이차방정식과 판별식의 이해
일반적인 이차방정식은 ax² + bx + c = 0 형태로 표현됩니다. 이때 판별식(D = b² − 4ac)의 값에 따라 근의 성질이 아래와 같이 세 가지 경우로 나뉩니다.
세 가지 경우: b² < 4ac - 근이 실수가 아니며 복소수 형태입니다. b² = 4ac - 두 근은 모두 실수이며 서로 같습니다(중근). b² > 4ac - 두 근은 모두 실수이며 서로 다릅니다.
입력 예시
다음과 같은 입력이 주어졌다고 가정해 보겠습니다.
a = 1, b = 2, c = 3
출력 예시
위 입력에 대한 기대 출력은 다음과 같습니다.
The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
알고리즘
Step 1 - 시작합니다. Step 2 - double형 변수 6개(a, b, c, root_1, root_2, quadratic_equation)를 선언합니다. Step 3 - 사용자로부터 a, b, c 값을 입력받거나 미리 값을 정의합니다. Step 4 - 입력값을 읽어 들입니다. Step 5 - 조건문에서 판별식(quadratic_equation) 값이 0보다 큰지 확인하고, 참이면 근의 공식을 이용해 각 근을 계산하여 변수에 저장합니다. Step 6 - 결과를 화면에 출력합니다. Step 7 - 종료합니다.
예제 1: 사용자 입력으로 근 구하기
아래 예제에서는 Scanner 클래스를 사용해 사용자로부터 계수 a, b, c를 직접 입력받은 뒤, 판별식 값에 따라 세 가지 경우를 if-else 조건문으로 나누어 처리합니다.
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
double a, b, c, root_1, root_2, quadratic_equation;
double real_number, imaginary_number;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.print("Enter the value of a : ");
a = my_scanner.nextDouble();
System.out.print("Enter the value of b : ");
b = my_scanner.nextDouble();
System.out.print("Enter the value of c : ");
c = my_scanner.nextDouble();
quadratic_equation = b*b - 4*a*c ;
if (quadratic_equation > 0) {
root_1 = (-b + Math.sqrt(quadratic_equation)) / (2 * a);
root_2 = (-b - Math.sqrt(quadratic_equation)) / (2 * a);
System.out.format("root_1 = %.2f and root_2 = %.2f", root_1, root_2);
}
else
if (quadratic_equation == 0) {
root_1 = root_2 = -b / (2 * a);
System.out.format("root_1 = root_2 = %.2f;", root_1);
}
else {
real_number = -b / (2 * a);
imaginary_number = Math.sqrt(-quadratic_equation) / (2 * a);
System.out.println("The roots of the quadratic equation are");
System.out.printf("root_1 = %.2f+%.2fi", real_number, imaginary_number);
System.out.printf("\nroot_2 = %.2f-%.2fi", real_number, imaginary_number);
}
}
}
실행 결과
Required packages have been imported A scanner object has been defined Enter the value of a : 1 Enter the value of b : 2 Enter the value of c : 3 The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
a=1, b=2, c=3을 입력하면 판별식은 2² − 4×1×3 = −8로 0보다 작습니다. 따라서 프로그램은 실수부와 허수부를 분리해 복소수 형태의 두 근을 출력합니다.
예제 2: 값이 미리 정의된 경우
이번 예제에서는 사용자 입력 없이 계수 값이 코드 안에 미리 정의되어 있으며, 해당 값을 그대로 사용해 결과를 콘솔에 출력합니다.
public class QuadraticEquation {
public static void main(String[] args) {
double a, b, c, root_1, root_2, quadratic_equation;
double real_number, imaginary_number;
a = 1;
b = 2;
c = 3;
System.out.println("The three numbers are defined as " +a +", " +b +" and " +c);
quadratic_equation = b*b - 4*a*c ;
if (quadratic_equation > 0) {
root_1 = (-b + Math.sqrt(quadratic_equation)) / (2 * a);
root_2 = (-b - Math.sqrt(quadratic_equation)) / (2 * a);
System.out.format("root_1 = %.2f and root_2 = %.2f", root_1, root_2);
}
else
if (quadratic_equation == 0) {
root_1 = root_2 = -b / (2 * a);
System.out.format("root_1 = root_2 = %.2f;", root_1);
}
else {
real_number = -b / (2 * a);
imaginary_number = Math.sqrt(-quadratic_equation) / (2 * a);
System.out.println("The roots of the quadratic equation are");
System.out.printf("root_1 = %.2f+%.2fi", real_number, imaginary_number);
System.out.printf("\nroot_2 = %.2f-%.2fi", real_number, imaginary_number);
}
}
}
실행 결과
The three numbers are defined as 1.0, 2.0 and 3.0 The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
마무리
핵심은 Math.sqrt() 메서드로 제곱근을 계산하고, 판별식의 부호에 따라 if-else 조건문으로 세 가지 경우를 분기 처리하는 것입니다. 또한 System.out.printf()의 %.2f 포맷 지정자를 활용하면 소수점 둘째 자리까지 깔끔하게 결과를 표시할 수 있습니다. 이 패턴을 응용하면 삼차방정식처럼 더 높은 차수의 방정식 문제로도 확장할 수 있습니다.