编译单元1:
// solver.cpp 求解一元二次方程
#include <iostream>
#include <cmath>
using namespace std;
static double Delta(double a, double b, double c)
{
return b*b - 4*a*c;
}
int Solver(double a, double b, double c, double &x1, double &x2)
{
int flag = 0;
double d = Delta(a, b, c);
if(d >= 0)
{
d = sqrt(d);
x1 = (-b - d)/(2*a);
x2 = (-b + d)/(2*a);
flag = (d>0) ? 2 : 1;
}
return flag;
}
void ShowEquation(double a, double b, double c)
{
cout << "方程:" << a << "x^2";
if(b>0)
cout << " + " << b << "x";
else
cout << " - " << -b << "x";
if(c>0)
cout << " + " << c << " = 0 ";
else
cout << " - " << -c << " = 0 ";
}
void ShowSolution(int flag, double x1, double x2)
{
switch(flag)
{
case 0: cout << "无实数根。" << endl; break;
case 1: cout << "有重根:x1 = x2 = " << x1 << endl; break;
case 2: cout << "有两个根:x1 = " << x1
<< ", x2 = " << x2 << endl;
}
}
头文件:
// solver.h
#ifndef SOLVER_H
#define SOLVER_H //"挡驾"以避免重复定义
int Solver(double a, double b, double c, double &x1, double &x2);
void ShowEquation(double a, double b, double c);
void ShowSolution(int flag, double x1, double x2);
#endif
主函数所在编译单元:
// solverTesting.cpp
#include "solver.h"
int main()
{
double a=1, b=2, c=-3, x1, x2;
int flag;
flag = Solver(a, b, c, x1, x2);
ShowEquation(a, b, c);
ShowSolution(flag, x1, x2);
return 0;
}
运行结果: