java 求一元二次方程的根

来源:百度知道 编辑:UC知道 时间:2024/05/28 12:06:01
代码如下,运行时无法计算出结果,显示infinity 请教哪里出错

import java.math.*;
public class function
{
public static boolean boo;//------------------------------声明全局变量,再在函数内运算
double a,b,c,x;
public static double p;

public function(double a,double b,double c)
{
p=b*b-4*a*c;
if(p>=0)
{
// c=a*x*x+b*x;
boo=true;
}
else
{
// System.out.println("方程无实根");
boo=false;
}

}
double calculator1()
{
double s1;
s1=((-b)-Math.sqrt(p))/(2*a);
return s1;
}
double calculator2()
{
double s2;
s2=((-b)+Math.sqrt(p))/(2*a);
return s2;
}
public static void main(String args[])
{
function aa=new function(2.0,6.0,3.0);

//double s=aa.calculator2();
//gdouble ss=aa.calculator1();

准确的说:是错在了
System.out.println("方程的1根是"+aa.calculator1());
System.out.println("方程的2根是"+aa.calculator2());
这两句上,因为无法从静态上下文中引用非静态 变量a,b,c,因为你没在double 前声明static ,所以无法引用到a,b,c,的值.即使你在前加了static (static double a,b,c)下面main函数里引用的都为0.0
现修改如下:
import java.math.*;
public class Function
{
public static boolean boo;//------------------------------声明全局变量,再在函数内运算
static double a,b,c,x;
public static double p;

public Function(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
p=b*b-4*a*c;
if(p>=0)
{
// c=a*x*x+b*x;
boo=true;
}
else
{
// System.out.println("方程无实根");
boo=false;
}

}
double calculator1()
{
double s1;
s1=((-b)-Math.sqrt(p))/(2*a);
return s1;
}
double calculator2()
{
double s2;
s2=((-b)+Math.sqrt(p))/(2*a);
retu