Problem Description

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

The Input

輸入三個整數 a, b, c

The Output

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

Two same roots x=??

No real root

PS: 答案均為整數,若有兩個根則大者在前

Sample Input

1     3     -10
1     0     0
1     1     1

Sample Output

Two different roots x1=2 , x2=-5
Two same roots x=0
No real root

-----* Problem from【ZeroJudge, an Online Judge System For Beginners

My Answer

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include<iostream>
#include<cmath>
using namespace std;
int main(void)
{
  int a, b, c;
  while(cin>>a>>b>>c){
    int formula=b*b-4*a*c;
    if(formula>0){
      int rootA=(-b+(int)sqrt(b*b-4*a*c))/(2*a);
      int rootB=(-b-(int)sqrt(b*b-4*a*c))/(2*a);
      if(rootA<rootB){
        int temp=rootA;
        rootA=rootB;
        rootB=temp;
      }
      cout<<"Two different roots x1="<<rootA
          <<" , x2="<<rootB<<endl;
    }
    else if(formula==0){
      int root=(-b+(int)sqrt(b*b-4*a*c))/(2*a);
      cout<<"Two same roots x="<<root<<endl;
    }
    else cout<<"No real root"<<endl;
  }
  return 0;
}
 

 


arrow
arrow
    全站熱搜

    兔老大 發表在 痞客邦 留言(0) 人氣()