用JAVA写一个求解一元二次方程的类

2024-12-02 23:34:31
推荐回答(2个)
回答(1):

import java.util.Scanner;

public class equation {
public static void main(String[] args){
System.out.println("输入一元二次系数a,b,c:");
Scanner in=new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int c=in.nextInt();
double x1,x2;
int deta=b*b-4*a*c;
if(deta==0){
x1=x2=(-b)/(2*a);
System.out.println("x1="+x1);
System.out.println("x2="+x2);
}else{
double t=Math.sqrt(Math.abs(deta))/(2*a);
if(deta>0){
x1=(-b)/(2*a)+t;
x2=(-b)/(2*a)-t;
System.out.println("x1="+x1);
System.out.println("x2="+x2);
}else{
x1=(-b)/(2*a);
x2=(-b)/(2*a);
System.out.println("x1="+x1+"+"+t+"*i");
System.out.println("x2="+x2+"-"+t+"*i");
}
}
}
}

回答(2):

public double A(double db){
        if(db<0){
            double dou=-db;
            double res = Math.sqrt(dou);
            System.out.println("虚根:"+ -res);
            return -res;
        }
        double res = Math.sqrt(db);
        System.out.println("实根:"+ res);
        return res;
    }