浮点数与0比较-CSDN博客
本来摘录自上面的文章,用以学习!感谢!
#include <QString>
#include <QDebug>
#include <stdio.h>
int main()
{double x=3.6;printf("%.50f\n",x);system("pause");return 0;
}
3.60000000000000008881784197001252323389053344726562
十进制转二进制时,有可能有精度损失.
不是一味的减少,也可能增多.
浮点数本身存储的时候,在计算不尽的时候,会"四舍五入"
#include<stdio.h>
#include <stdio.h>
#include <windows.h>
int main()
{double x = 1.0;double y = 0.1;printf("%.50f\n", x - 0.9);printf("%.50f\n", y);if ((x - 0.9) == y) {printf("you can see me!\n");}else {printf("oops\n");}system("pause");return 0;
}
0.09999999999999997800000000000000000000000000000000
0.10000000000000001000000000000000000000000000000000
oops
浮点数精度有损失.
不可以使用==来进行比较
应使用范围精度比较
最小误差
#define DBL_EPSILON 2.2204460492503131e-016
/* smallest such that 1.0+DBL_EPSILON != 1.0*/
#define FLT_EPSILON 1.192092896e-07F/* smallest such that 1.0+FLT_EPSILON != 1.0*/
有点看不懂啦!
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <windows.h>
int main()
{
double x = 0.00000000000000000000001;
//if (fabs(x-0.0) < DBL_EPSILON){ //写法1
//if (fabs(x) < DBL_EPSILON){ //写法2
if(x > -DBL_EPSILON && x < DBL_EPSILON){ //书中写法
printf("you can see me!\n");
}
else{
printf("oops\n");
}
return 0;
}
you can see me!
/* The difference between 1 and the least value greater than 1 that isrepresentable in the given floating point type, b**1-p. */
#undef FLT_EPSILON
#undef DBL_EPSILON
#undef LDBL_EPSILON
#define FLT_EPSILON __FLT_EPSILON__
#define DBL_EPSILON __DBL_EPSILON__
#define LDBL_EPSILON __LDBL_EPSILON__