求方程ax2+bx+c=0的根,用3个函数分别求当b2-4ac大于0、等于0和小于0时的根,并输出结果。从主函数输入a,b,c的值。
#include <iostream>
#include <math.h>
using namespace std;
void greater_than_zero(float, float);
void equal_to_zero(float, float);
void smaller_than_zero(float, float);
float x1, x2, disc, p, q;
int main()
{
float a, b, c;
cout << "input a,b,c:";
cin >> a >> b >> c;
disc = b * b - 4 * a*c;
cout << "reuslt:" << endl;
if (disc > 0)
{
greater_than_zero(a, b);
cout << "x1=" << x1 << ",x2=" << x2 << endl;
}
else if (disc == 0)
{
equal_to_zero(a, b);
cout << "x1=" << x1 << ",x2=" << x2 << endl;
}
else
{
smaller_than_zero(a, b);
cout << "x1=" << p << "+" << q << "i" << endl;
cout << "x2=" << p << "-" << q << "i" << endl;
}
system("pause");
return 0;
}
void greater_than_zero(float a, float b)
{
x1 = (-b + sqrt(disc)) / (2 * a);
x2 = (-b - sqrt(disc)) / (2 * a);
}
void equal_to_zero(float a, float b)
{
x1 = x2 = (-b) / (2 * a);
}
void smaller_than_zero(float a, float b)
{
p = -b / (2 * a);
q = sqrt(-disc) / (2 * a);
}