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);
}
}
}
다음은 실행화면이다.

'Java 언어' 카테고리의 다른 글
| Java, Hello World 프로그램을 Jar 파일로 만들기 (Java Swing 프로그램) (0) | 2021.09.25 |
|---|---|
| Java, Jar 파일 만들기 (콘솔 프로그램) (0) | 2021.09.25 |
| Java로 스도쿠 게임 만들기(스도쿠 문제) (1) | 2021.09.20 |
| Java로 Hello world! 출력하기 (1) | 2021.01.29 |
| OPENJDK 설치하기 (1) | 2021.01.29 |
댓글