要求用文本数据流的方式输入a、b、c,求一元二次方程的根。
怎么实现?

解决方案 »

  1.   


    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;public class Main {    public static void main(String[] args) {        double x1,x2;
            double a,b,c;
            InputStreamReader  ins = new InputStreamReader (System.in);
            BufferedReader  br = new BufferedReader (ins);
            
            a = 0;
            b = 0;
            c = 0;
            x1= 0;
            x2= 0;        try {
            
                System.out.println("Please input a(user ENTER end input)");
                a = Double.parseDouble(br.readLine());
                
                System.out.println("Please input b(user ENTER end input)");
                b = Double.parseDouble(br.readLine());
                
                System.out.println("Please input c(user ENTER end input)");
                c = Double.parseDouble(br.readLine());            
            
            } catch (IOException ex) {
            
                ex.printStackTrace();
                
            }        x1 = ((0-b)+Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);
            x2 = ((0-b)-Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);        System.out.println("x1 = " + x1);
            System.out.println("x2 = " + x2);
        }
    }
      

  2.   

    2楼正解。
      x1 = ((0-b)+Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);
      x2 = ((0-b)-Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);
    改为if(math.pow(b,2)-4*a*c>=0){
      x1 = ((0-b)+Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);
      x2 = ((0-b)-Math.pow((Math.pow(b, 2)-4*a*c), 0.5)) / (2 * a);
      System.out.println("x1 = " + x1);
      System.out.println("x2 = " + x2);
    }else System.out.println("No root!");
    或者try-catch一下也行