一元二次方程求根

一、題目要求

  • 題目要求: 要求讀入一元二次方程的3個係數A、B、C,然後輸出。
  • 輸入要求:如果只有一個解單行輸出,若果有多個解,用逗號隔開。

二、代碼實現

import java.util.Scanner;

import static java.lang.Math.sqrt;

public class example03 {

    public static double Fun(int a , int b ,int c) {
        double z = 0;
        if ((b * b - 4 * a * c) > 0) {
            z = sqrt(b * b - 4 * a * c);
            return z;
        }
        else if((b * b - 4 * a * c) == 0){
          return 0;
        }else{
            return -1;
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt()){
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            double z = Fun(a,b,c);
            if(z>0){
                double k1 = (-b+z)/(2*a);
                double k2 = (-b-z)/(2*a);
                System.out.println("x1="+String.format("%.2f", k1)+","+"x2="+String.format("%.2f", k2));
            }
            else  if(z == 0){
                double k1 = (-b)/(2*a);

                System.out.println("x="+ String.format("%.2f", k1));
            }
            else{

            }
        }

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章