Create a java program to solve quadratic equations

二次信任 提交于 2019-12-04 19:14:32

Firstly, your code won't compile--you have an extra } after the start of public static double quadraticEquationRoot1(int a, int b, int c) ().

Secondly, you aren't looking for the correct input types. If you want input of type double, make sure you declare the method appropriately. Also be careful of declaring things as int when they could be doubles (for example, root1 and root2).

Thirdly, I don't know why you have the if/else block--it would be better to simply skip it, and only use the code that is currently in the else part.

Finally, to address your original question: Simply create a separate method and use Math.min() instead of Math.max().

So, to recap in code:

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!
}

Well why don't you try to use the same exact algorithms but then use Math.min in your return statement?

Also, note that you're not taking into account whether or not $b$ is negative in your first if statement. In other words you simply return $-b / 2a$ but you don't check if $b$ is negative, if it isn't then this is actually the smaller of the two roots not the larger. Sorry about that! I misinterpreted what was going on xD

Ahmed Rakha
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 !!!");
        }
    }        
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!