编写一个类,该类封装了一元二次方程共有的属性和功能,即该类有刻画方程系数的3个成员变量以及计算实根的方法。
package practice1;public class Pratice1 {
private double a;
private double b;
private double c;
private double[] d;
public String[] i;
public void setValue(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
this.d = new double;
this.i = new String;
}
public boolean canGetValue() {
double temp;
temp = b * b - 4 * a * c;
if (temp < 0) {
this.i = (-b) / (a * 2) + "+" + Math.sqrt(-temp) / (2 * a) + "i";
this.i = (-b) / (a * 2) + "-" + Math.sqrt(-temp) / (2 * a) + "i";
return false;
} else {
this.d = (-b + Math.sqrt(temp)) / (2 * a);
this.d = (-b - Math.sqrt(temp)) / (2 * a);
return true;
}
}
/**
* @param args
*/
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public double getD(int i) {
return d;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Pratice1 pratice1 = new Pratice1();
pratice1.setValue(1, 3, 4);
if (pratice1.canGetValue()) {
System.out.println(pratice1.getA());
System.out.println(pratice1.getB());
System.out.println(pratice1.getC());
System.out.println(pratice1.getD(0));
System.out.println(pratice1.getD(1));
} else {
System.out.println(pratice1.i);
System.out.println(pratice1.i);
}
}
}
页:
[1]