创建一个java程序来解决二次方程

求解二次方程

到目前为止,我已写下以下内容。 我不确定如何引入第二种方法

public static void main(string args[]){ } public static double quadraticEquationRoot1(int a, int b, int c) (){ } if(Math.sqrt(Math.pow(b, 2) - 4*a*c) == 0) { return -b/(2*a); } else { int root1, root2; root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a); root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a); return Math.max(root1, root2); } } 

首先,在public static double quadraticEquationRoot1(int a, int b, int c) ()开始之后,你的代码将无法编译 – 你有一个额外的}

其次,您没有寻找正确的输入类型。 如果要输入double类型,请确保正确声明方法。 当它们可能是双精度时(例如, root1root2 ),也要小心将事物声明为int

第三,我不知道为什么你有if/else块 – 最好只是跳过它,并且只使用当前在else部分的代码。

最后,要解决您的原始问题:只需创建一个单独的方法并使用Math.min()而不是Math.max()

所以,回顾一下代码:

 public static void main(string args[]){ } //Note that the inputs are now declared as doubles. public static double quadraticEquationRoot1(double a, double b, double c) (){ double root1, root2; //This is now a double, too. root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a); root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a); return Math.max(root1, root2); } public static double quadraticEquationRoot2(double a, double b, double c) (){ //Basically the same as the other method, but use Math.min() instead! } 

那么为什么不尝试使用相同的算法,然后在return语句中使用Math.min?

另请注意,您没有考虑第一个if语句中$ b $是否为负数。 换句话说,你只需返回$ -b / 2a $,但你不检查$ b $是否为负数,如果不是那么这实际上是两个根中的较小者而不是较大的。 对于那个很抱歉! 我误解了xD上发生了什么

 package QuadraticEquation; import javax.swing.*; public class QuadraticEquation { public static void main(String[] args) { String a = JOptionPane.showInputDialog(" Enter operand a : "); double aa = Double.parseDouble(a); String b = JOptionPane.showInputDialog(" Enter operand b : "); double bb = Double.parseDouble(b); String c = JOptionPane.showInputDialog(" Enter operand c : "); double cc = Double.parseDouble(c); double temp = Math.sqrt(bb * bb - 4 * aa * cc); double r1 = ( -bb + temp) / (2*aa); double r2 = ( -bb -temp) / (2*aa); if (temp > 0) { JOptionPane.showMessageDialog(null, "the equation has two real roots" +"\n"+" the roots are : "+ r1+" and " +r2); } else if(temp ==0) { JOptionPane.showMessageDialog(null, "the equation has one root"+ "\n"+ " The root is : " +(-bb /2 * aa)); } else{ JOptionPane.showMessageDialog(null, "the equation has no real roots !!!"); } } }