//求一元二次方程式ax^2+bx+c=0;
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a = 0, b = 0, c = 0;
double ans1 = 0, ans2 = 0;
while (cin >> a >> b >> c)
{
ans1 = (-b + sqrt((b*b) - (4 * a*c))) / (2 * a);
ans2 = (-b - sqrt((b*b) - (4 * a*c))) / (2 * a);
if (b*b - 4 * a*c < 0)
{
cout << "No real root" << endl;
}
else // b^2-4ac>=0
{
if (ans1 != ans2 && ans1 > ans2)
{
cout << "Two different roots x1=" << ans1 << " , x2=" << ans2 << endl;
}
else if (ans1 != ans2 && ans2 > ans1)
{
cout << "Two different roots x1=" << ans2 << " , x2=" << ans1 << endl;
}
else if (ans1 == ans2)
{
cout << "Two same roots x=" << ans1 << endl;
}
}
}
system("PAUSE");
return 0;
}
//求一元二次方程式ax^2+bx+c=0;
#include
#include
using namespace std;
int main()
{
int a = 0, b = 0, c = 0;
double ans1 = 0, ans2 = 0;
while (cin >> a >> b >> c)
{
ans1 = (-b + sqrt((b*b) - (4 * a*c))) / (2 * a);
ans2 = (-b - sqrt((b*b) - (4 * a*c))) / (2 * a);
if (b*b - 4 * a*c < 0)
{
cout << "No real root" << endl;
}
else // b^2-4ac>=0
{
if (ans1 != ans2 && ans1 > ans2)
{
cout << "Two different roots x1=" << ans1 << " , x2=" << ans2 << endl;
}
else if (ans1 != ans2 && ans2 > ans1)
{
cout << "Two different roots x1=" << ans2 << " , x2=" << ans1 << endl;
}
else if (ans1 == ans2)
{
cout << "Two same roots x=" << ans1 << endl;
}
}
}
system("PAUSE");
return 0;
}
sqrt( (b*b) - (4 * a*c) )
若是小於0,應該會變成複數的感覺,雖然應該不太會影響答案,只是覺得不太好
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a,b,c;
while(cin>>a>>b>>c){
int cal = b*b-4*a*c;
if (cal < 0){
cout << "No real root\n";
}
else if (cal == 0){
cout << "Two same roots x=" << (-1)*b/(2*a) << endl;
}
else{
cout << "Two different roots x1=" << ((-1)*b+sqrt(cal))/(2*a);
cout << " , x2=" << ((-1)*b-sqrt(cal))/(2*a) << endl;
}
}
return 0;
}