求一元二次方程式 ax2+bx+c=0 的根
輸入說明 : 
輸入三個整數 a, b, c
輸出說明 : 
Two different roots x1=?? , x2=??
Two same roots x=??
No real root
PS: 答案均為整數,若有兩個根則大者在前
Two same roots x=??
No real root
PS: 答案均為整數,若有兩個根則大者在前
範例輸入 : 
1 3 -10 1 0 0 1 1 1
範例輸出:
Two different roots x1=2 , x2=-5 Two same roots x=0 No real root
提示 : 
標籤:
import java.util.*;
public class a006 {                
   public static void main(String[] args) {
       int a,b,c;
       double answer_1,answer_2;
       int test;
       Scanner sc=new Scanner(System.in);
       while(sc.hasNext()){
          a=sc.nextInt();
          b=sc.nextInt();
          c=sc.nextInt();
          answer_1=((b*-1)+Math.sqrt(b*b-4*a*c))/(2*a);
          answer_2=((b*-1)-Math.sqrt(b*b-4*a*c))/(2*a);
          test=b*b-4*a*c;  //檢查無整數答案用
         if(test>=0){
              if(answer_1!=answer_2){
                   if(answer_1>answer_2)
                      System.out.println("Two different roots x1="+(int)answer_1+" , x2="(int)answer_2);
                  else
                      System.out.println("Two different roots x1="+(int)answer_2+" , x2="+ (int)answer_1);
            }
            else 
              System.out.println("Two same roots x="+(int)answer_1);
       }
       else{
             System.out.println("No real root");
        }
     }
  }
}
最後一個else顯示錯誤不知道為甚麼?
回覆刪除