如何判断两个浮点数(float类型)是否相等?(转)

今天在面试中碰到这个问题,当时还迷糊了一番,毕竟平时没怎么用过,记得以前看过,现在有点记不清了!这是C语言很基础的东西,面试一般会遇到!

对两个浮点数判断大小和是否相等不能直接用==来判断,会出错!明明相等的两个数比较反而是不相等!

对于两个浮点数比较只能通过相减并与预先设定的精度比较,记得要取绝对值!

 

[cpp] view plaincopy
 
  1. if( fabs(f1-f2) < 预先指定的精度)  
  2. {  
  3.       ...  
  4. }  


例子

 

 

[cpp] view plaincopy
 
  1. #define EPSILON 0.000001 //根据精度需要  
  2. if ( fabs( fa - fb) < EPSILON )  
  3. {  
  4.      printf("fa<fb\n");  
  5. }  

 

fabs函数与abs函数

数学函数:fabs
原型:extern float fabs(float x);
  
  用法:#include <math.h>
  
  功能:求浮点数x的绝对值
  
  说明:计算|x|, 当x不为负时返回x,否则返回-x
  
  举例:

 

[cpp] view plaincopy
 
  1. // fabs.c  
  2.     
  3.   #include <syslib.h>  
  4.   #include <math.h>  
  5.   
  6.   main()  
  7.   {  
  8.     float x;  
  9.       
  10.     clrscr();        // clear screen  
  11.     textmode(0x00);  // 6 lines per LCD screen  
  12.       
  13.     x=-74.12;  
  14.     printf("|%f|=%f\n",x,fabs(x));  
  15.     x=0;  
  16.     printf("|%f|=%f\n",x,fabs(x));  
  17.     x=74.12;  
  18.     printf("|%f|=%f\n",x,fabs(x));  
  19.       
  20.     getchar();  
  21.     return 0;  
  22.   }  

 

 

abs函数是针对整数的
[cpp] view plaincopy
 
  1. #include <stdio.h>  
  2. #include <math.h>  
  3. int main()  
  4. {  
  5.  int x=-10;  
  6.  printf("%d",abs(x));  
  7. }  



 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-03 19:53  hbg-rohens  阅读(2666)  评论(0编辑  收藏  举报