# 解一元二次方程式

YTC
c_cpp
2 years ago
2.1 kB
3
Indexable
Never
```//
//  main.cpp
//
//  Created by YTC on 2022/3/9.
//
#include <iostream>
#include <cmath>

using namespace std;

int main() {
double a,b,c,x1,x2,realpart,imaginarypart;

cout<<">>請輸入一元二次程式之係數 a, b, 和 c:"<<endl;

cin >> a >> b >> c;
double discriminant = b*b-4*a*c; //discriminant 為判別式

cout<<"您所輸入之一元二次方程式如下：\n";
cout<<a<<"x^2"<<"+"<<b<<"x"<<"+"<<c<<" = 0"<<endl;

if(a == 0){
if(b == 0)
{
if(c == 0)
{
cout<<"全部都0是在打心酸的？？"<<endl;
}
else{
cout<<"ERROR occur"<<endl;
}
}

else{
if(c == 0){  //(a, b, c) = (0, 1, 0)
x1 = c/b;
cout<<"有一根："<< x1 <<endl;

}
else {
x1 = -c/b; // bx = -c
cout<<"有一根："<< x1 <<endl;
}
}
}

else{

if(discriminant>0)
{
x1 = (-b+sqrt(discriminant))/2*a;
x2 = (-b-sqrt(discriminant))/2*a;
cout<<"有兩相異實根："<<x1<<","<<x2<<endl;
}

else if(discriminant == 0)
{
x1 = -b/2*a;
cout<<"有兩相同實根："<< x1 <<"," << x1 <<endl;
}

else if(discriminant < 0)
{
realpart = -b/2*a;
imaginarypart = sqrt(abs(discriminant))/2*a;
cout<<"有兩虛根（或無實根）："<<realpart<<'+'<<imaginarypart<<"i"<<","<< realpart << -imaginarypart << "i"<<endl;
}
}
char again;
cout<<"是否要繼續？（y/n)"<<endl;
cin >> again;
if(again == 'y' || again =='Y'){
return main();
}
else if(again == 'n' || again == 'N'){
return 0;
}
}
```