求ax^2+bx+c=0的根
源程序为:
#include <stdio.h>
#include <math.h>
/*浮点数不精确:用有限的存储单元存储一个实数,不可能完全精确的存储,需要定义误差*/
#include <float.h> //定义误差使用的头文件
# define EPS 0.0000001 //定义误差,使其在范围内为0
void fun ( int a ,int b ,int c) //定义求根函数
{
double x1,x2,d = b*b-4*a*c;
if ( -EPS <= a && a <= EPS ) //a=0时
{
x1 = x2 = (-c) / b;
printf(" x1=%f,x2=%f\n ",x1,x2);
}
else //a!=0时
{
if ( d>EPS ) //d>0时
{
x1=( -b + sqrt (d) ) / ( 2*a );
x2=( -b - sqrt (d) ) / ( 2*a );
printf (" x1=%f,x2=%f \n ", x1 , x2 );
}
else if (-EPS <=d && d<=EPS) //d为0时
{
x1 = x2 = -b / ( 2*a );
printf (" x1=%f,x2=%f\n ", x1, x2);
}
else //d<0时
{
printf("此方程无根\n");
}
}
}
int main()
{
fun(1,2,3);
fun(1,2,1);
fun(0,2,3);
fun(1,1,3);
return 0;
}