繁体   English   中英

创建一个Java程序来求解二次方程

[英]Create a java program to solve quadratic equations

求解二次方程

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

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类型的输入,请确保适当地声明该方法。 当它们可能是双精度时,也要小心地将它们声明为int (例如, root1root2 )。

第三,我不知道为什么会有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 !!!");
        }
    }        
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM