我需要编写一个代码来解决二次方程并在没有解决方案的情况下显示一条消息,当我运行程序时,无论我使用什么数字,我总是得到第三个if语句,其中没有解决方案。
public class Quadratic {
private double a, b, c, x, x1, x2;
public Quadratic() {
a = b = c = 1;
}
public Quadratic(double a1, double b1, double c1) {
a = a1;
b = b1;
c = c1;
}
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public void setA(double a2) {
a = a2;
}
public void setB(double b2) {
b = b2;
}
public void setC(double c2) {
c = c2;
}
public void setQuadratic(double a3, double b3, double c3) {
a = a3;
b = b3;
c = c3;
}
public void roots() {
System.out.println(a + "x^2 + " + b + "x + " + c + " = 0");
if (Math.pow(b, 2) - 4 * a * c == 0) {
System.out.println("Solution: (" + oneSolution() + ")");
}
if (Math.pow(b, 2) - 4 * a * c > 0) {
System.out.println("Solutions: (" + solution1() + "," + solution2() + ")");
}
if (Math.pow(b, 2) - 4 * a * c < 0) {
System.out.println("Solutions: There are no solutions");
}
}
public double oneSolution() {
x = -b / 2 * a;
return x;
}
public double solution1() {
x1 = (-b + (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / (2 * a);
return x1;
}
public double solution2() {
x2 = (-b - (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / (2 * a);
return x2;
}
}
答案 0 :(得分:1)
您的代码似乎有用: - )
我上了你的课并做了以下事情:
class Test {
public static void main(String[] args) {
Quadratic q = new Quadratic(1.0, 2.0, -35.0);
q.roots();
}
}
输出结果为:
1.0x^2 + 2.0x + -35.0 = 0
Solutions: (5.0,-7.0)
这是正确的!
答案 1 :(得分:0)
尝试使用2.或2.0而不是2:2.0,4.0等... 如果这不起作用,请尝试2.0d等,或声明你的常量:double two = 2.0;
也许这会使它工作,我不确定Java处理,例如double / integer ..所以你可能更好地做一个double / double