Skip to content

[ACM]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顯示

出處 :http://zerojudge.tw/ShowProblem?problemid=a007

程式碼:

#include <iostream>
#include <math.h>
using namespace std;
int a,b,c,sun,sunb,suna,tb;
int main()
{
 cin>>a>>b>>c;
 tb=b-b-b;
 sun=pow(b,2)-(4*a*c);
 suna=(tb+sqrt(sun))/(a*2);
 sunb=(tb-sqrt(sun))/(a*2);
 if (sun<0)
 {
  cout<<"No real root"<<endl;
 }
 else if(sun==0)
 {
  cout<<"Two same roots x="<<tb/(2*a)<<endl;  }  else if(sun>0 and suna>sunb)
 {
  cout<<"Two different roots x1="<<suna<<" , x2="<<sunb<<endl;  }  else if(sun>0 and suna<sunb)
 {
  cout<<"Two different roots x1="<<sunb<<" , x2="<<suna<<endl;
 }
 return 0;
}
Published inACM解題

Be First to Comment

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *