在生活中解决实际问题时,存在误差是在所难免的,当然,浮点类型的数也存在误差,当 遇到float,double和整型数比较大小时,并不仅仅时简单的将两个数放在一起比较了。要考虑到误差。
例如 : 求 ax^2+bx+c=0 的实根
代码:
#include <stdio.h>
#include <math.h>
#define EPS 0.00000001 //误差
void Fun( double a,double b, double c)
{
double x1;
double x2;
double m = b*b-4*a*c;
if( -EPS <= a && a <=EPS) //a==0
{
printf("%f \n",-c/b);
}
else if ( m >= EPS) //m>=0
{
x1=-b+sqrt(m)/(2*a);
x2=-b-sqrt(m)/(2*a);
printf("%f %f \n",x1,x2);
}
else if( m<-EPS) //m<0
{
printf("无实根\n");
}
}
int main()
{
Fun(2, 4,2);
Fun(2, 3,2);
return 0;
}
在这个题中,a,b,c,都是浮点类型的数,当判断a是否等于0时,就不能直接写成 a==0,
因此我们定义 EPS表示误差 ,与0的比较如下图所示;