a006. 一元二次方程式
求一元二次方程式 ax2+bx+c=0 的根
解題方案:
公式解讚!先算判別式 D = b2 - 4ac
D > 0: 兩相異根
D = 0: 重根
D < 0: 無解
在開根號之後要型態轉換成int,原本是double的但是題目很貼心只會出整數。
像這種題目Two different rootsasdfh2kq3ras.f.asd
什麼的就不要用手打了,直接複製題目上面的說明,免得打錯。
程式碼如下:
- import java.util.Scanner;
- public class Pa006{
- public static void main(String[] args){
- Scanner scanner = new Scanner(System.in);
- while(scanner.hasNext()){
- int a = scanner.nextInt();
- int b = scanner.nextInt();
- int c = scanner.nextInt();
- int D = b * b - 4 * a * c;
- if (D > 0){
- System.out.printf("Two different roots x1=%d , x2=%d%n", ( -b + (int)Math.sqrt(D) ) / 2 / a, ( -b - (int)Math.sqrt(D) ) / 2 / a);
- }else if (D == 0){
- System.out.printf("Two same roots x=%d%n", -b / 2 / a);
- }else{
- System.out.println("No real root");
- }
- }
- }
- }
沒有留言:
張貼留言