Giải phương trình bậc 2

Yêu cầu
– Nhập vào số thực a, b, c là hệ số của phương trình bậc 2
– Tính nghiệm của phương trình.

Giải thuật
– Tính nghiệm theo delta = b*b – 4*a*c

Code

package net.vncoding;
import java.util.Scanner;
import java.lang.Math;

public class JavaCore {

    public static void main(String[] args) {
        
        float a, b, c, x1, x2;
        float delta = 0;
        Scanner sc = new Scanner(System.in);;
        
        System.out.print("Input a = ");
        a = sc.nextFloat();
        
        System.out.print("Input b = ");
        b = sc.nextFloat();
        
        System.out.print("Input b = ");
        c = sc.nextFloat();
        
        delta = b*b - 4*a*c;
        
        if(delta == 0)
            System.out.println("Phuong trinh co nghiem kep = " + (-b)/(2*a));
        else if(delta < 0)
            System.out.println("Phuong trinh vo nghiem");
        else{
            x1 = (float) ((-b + Math.sqrt(delta))/(2*a));
            x2 = (float)((-b - Math.sqrt(delta))/(2*a));
            System.out.println("Nghiem thu nhat x1 = " + x1);
            System.out.println("Nghiem thu hai x2 = " + x2);
        }
        
        sc.close();
    }
}

Kết quả

Java - Giải phương trình bậc 2
Java – Giải phương trình bậc 2

Be the first to comment

Leave a Reply