C语言中浮点数double/float相等判断
#include <stdio.h> #include <math.h> /* fabs */ #ifdef _WIN32 // #include <Windows.h> #endif //输出的数值不断递增,即使将10改成10.0,循环也没有中止,为什么? void test_float001() { double i; for(i=0; i != 10; i += 0.1) { printf("%.1f ", i); #ifdef _WIN32 Sleep(100); #endif } } //https://www.zhihu.com/question/32304267 //按不同精度输出 void test_float002() { double i; int j; for(i = 0, j = 0; j != 101; j++, i += 0.1) { printf("%.20lf %.1f ", i, i); #ifdef _WIN32 Sleep(100); #endif } //因为十进制浮点数无法转化为精确的二进制浮点数,所以,你得到的结果注定是不精确的,所以累加以后也永远得不到精确的10.0 } //1、float double浮点型相等判断。 /* a == b*/ int dequals(double a, double b) { double c=fabs(a-b);//一定要#include <math.h> labs 针对long整数 fabs针对浮点数,abs针对整数 return c< 0.000001; } void test_abs() { int c=-3; float b=-4.3; printf("c的绝对值:%d ",abs(c)); printf("b的绝对值:%ld ",fabs(b)); printf("b的绝对值:%f ",fabs(b)); printf ("The absolute value of 3.1416 is %f ", fabs(3.1416)); printf ("The absolute value of -10.6 is %f ", fabs(-10.6)); } //C语言中浮点数double/float相等判断 int main(void) { test_abs(); double a=0.89999999999999991000; double b=0.9; if(a==b) { printf("a==b "); }else{ printf("a!=b "); } b=0.89999999999999992200;//后面的精度就是接近值了 if(a!=b)//这里居然是相等的 { printf("a!=b "); }else{ printf("a==b "); } if(dequals(a,b)) { printf("a==b "); }else{ printf("a!=b "); } if (abs(a - b)<0.0001) { printf("a==b "); }else{ printf("a!=b "); } // test_float001(); test_float002(); return 0; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: html嵌套php:switch
- 下一篇: C语言声明一维动态数组