4. เลือกปฏิบัติ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 4-22  โปรแกรมหารากของสมการกำลังสอง ax2 + bx + c
import java.util.Scanner;  
// โปรแกรมหารากของสมการ ax2 + bx + c = 0
public class QuadraticRoots {
 public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("a = ");
    double a = kb.nextDouble();
    System.out.print("b = ");
    double b = kb.nextDouble();
    System.out.print("c = ");
    double c = kb.nextDouble();
    boolean isTrivial  = (a == 0 && b == 0 && c == 0);
    boolean noSolution = (a == 0 && b == 0 && c != 0);
    boolean isLinear   = (a == 0 && b != 0);
    boolean isComplex  = (b*b < 4*a*c);
    if (isTrivial) {
      System.out.println("รากคือจำนวนใด ๆ");  
    } else if (noSolution) {
      System.out.println("สมการนี้ไม่มีราก");
    } else if (isLinear) {
      System.out.println("รากคือ " + (-c / b));
    } else if (isComplex) {
      System.out.println("รากเป็นจำนวนเชิงซ้อน (โปรแกรมนี้หาให้ไม่ได้)");
    } else {
      double t = Math.sqrt(b*b - 4*a*c);
      double r1 = (-b + t) / (2*a);
      double r2 = (-b - t) / (2*a);
      System.out.print("รากคือ " + r1);
      if (r1 != r2) System.out.print(" และ " + r2);
      System.out.println();
    }
  }
}
©2009 S.Prasitjutrakul