java求方程根代码 java 求根( 二 )


public class Test30009{
public static void main(String args[]){
int repeat, ri;
int a,b,c,d;
double x1 = 0,x2;
Scanner in=new Scanner(System.in);
repeat=in.nextInt();
for(ri = 1; ri = repeat; ri++){
a=in.nextInt();b=in.nextInt();c=in.nextInt();
d=b*b-4*a*c;
if(a==0b==0c==0)
System.out.println("a=b=c=0,meaningless");
else if(a==0b==0)
System.out.println("a=b=0,c!=0,error");
else if(a==0){
x1=-c*1.0/b;
System.out.println("x="+String.format("%.2f", x1));
}else if(d0||d==0){
x1=(-b+Math.sqrt(d))/(2*a);
x2=(-b-Math.sqrt(d))/(2*a);
System.out.println("x1="+String.format("%.2f", x1));
System.out.println("x2="+String.format("%.2f", x2));
}else{
x1=-b*1.0/(2*a);
x2=Math.sqrt(-d)/(2*a);
System.out.println("x1="+String.format("%.2f", x1)+"+"+String.format("%.2f", x2)+"i");
System.out.println("x2="+String.format("%.2f", x1)+"-"+String.format("%.2f", x2)+"i");
}
}
}
}
java 求一元二次方程的根准确的说:是错在了
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);
return s2;
}
public static void main(String args[])
{
Function aa=new Function(2.0,6.0,3.0);
//System.out.println(boo);
System.out.println(b);//你可以多写这样的语句进行测试
if(boo)
{
System.out.println("方程的1根是"+aa.calculator1());
System.out.println("方程的2根是"+aa.calculator2());
}
else
{
System.out.println("方程无实根");
}
}
}
运行结果://true
//6.0
方程的1根是-2.3660254037844384
方程的2根是-0.6339745962155614
哈哈,总之是static没用好,给分吧快 。
用JAVA定义一个一元二次方程?以下是定义一元二次方程类、封装系数及其求根方法的示例代码:
public class Equation {
private double a;
private double b;
private double c;
// 封装系数
public void setA(double a) {
this.a = a;
}
public double getA() {
return a;
}
public void setB(double b) {
this.b = b;
}
public double getB() {
return b;
}
public void setC(double c) {
this.c = c;
}
public double getC() {
return c;
}
// 求根方法
public void solve() {
double delta = b * b - 4 * a * c;
if (delta0) {
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
System.out.println("方程的两个解分别为:" + x1 + "和" + x2);
} else if (delta == 0) {
double x = -b / (2 * a);
System.out.println("方程的解为:" + x);
} else {
System.out.println("方程无解");
}
}

推荐阅读