2014年9月26日 星期五

a006:一元二次方程式

內容

求一元二次方程式 ax2+bx+c=0 的根


輸入說明

輸入三個整數 a, b, c

輸出說明

Two different roots x1=?? , x2=??

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

提示

背景知識: 判斷

* double 宣告 * 本系統以 Linux g++ 進行編譯,請注意 -0 的現象,應改為0顯示

出處

Jiangsir

解題:

import java.util.Scanner;
public class a006
{
        public static void main(String[] args)
        {
                Scanner scan = new Scanner(System.in);
                int a=0;
                int b=0;
                int c=0;
                int x1=0;
                int x2=0;
                int tmp=0;
                while(scan.hasNext())
                {
                        a=scan.nextInt();
                        b=scan.nextInt();
                        c=scan.nextInt();
                        tmp=b*b-4*a*c;
                        if(tmp<0)
                        {
                                System.out.println("No real root");
                        }
                        else if(tmp==0)
                        {
                                tmp=(int)Math.sqrt(tmp);
                                x1=(0-b)/(2*a);
                                System.out.println("Two same roots x="+x1);
                        }
                        else if(tmp>0)
                        {
                                tmp=(int)(Math.sqrt(tmp));
                                x1=(0-b+tmp)/(2*a);
                                x2=(0-b-tmp)/(2*a);
                                if(x1>x2)
                                {
                                        System.out.println("Two different roots x1="+x1+" , x2="+x2);
                                }
                                else if(x2>x1)
                                {
                                        System.out.println("Two different roots x1="+x2+" , x2="+x1);
                                }
                        }
                }
        }

}


如果您喜歡我的文章,請在文章最末按5下Like!
我將得到LikeCoin的回饋:)

回饋由LikeCoin基金會出資,您只要註冊/登入帳號(FB、Google帳號都可以註冊,流程超快),按L五次左鍵,可以贊助我的文章且完全不會花到錢!
支持創作,正向交流:)

沒有留言:

張貼留言