class FindRoot{ //计算一元二次方程的根
static double[] root(double a, double b, double c) throws Exception
{
double x[]=new double[2];
if (a== 0)
{
throw new Exception("a 不能为零.");
}
else{
double disc = (b*b) - 4*a*c;
if (disc < 0)
throw new Exception("b*b-4ac值不能小于零.");
x[0]=(-b + Math.sqrt(disc)) / (2*a);
x[1]=(-b - Math.sqrt(disc)) / (2*a) ;
return x;
}
}
public static void main(String arg[]) {
try {
double x[] = root(2.0,-3.0,1); //a,b,c
System.out.println("方程2*x*x-3*x+1=0的根为:" +x[0]+","+x[1]);
}
catch(Exception e) { System.out.println(e); }
}
}
java——计算一元二次方程的根
最新推荐文章于 2023-12-24 00:00:00 发布