C语言中浮点数double/float相等判断

161 篇文章 10 订阅
#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\n", 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\t %.1f\n", 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\n",abs(c));
    printf("b的绝对值:%ld\n",fabs(b));
    printf("b的绝对值:%f\n",fabs(b));


    printf ("The absolute value of 3.1416 is %f\n", fabs(3.1416));
    printf ("The absolute value of -10.6 is %f\n", 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\n");
    }else{
        printf("a!=b\n");
    }

    b=0.89999999999999992200;//后面的精度就是接近值了
    if(a!=b)//这里居然是相等的
    {
        printf("a!=b\n");
    }else{
        printf("a==b\n");
    }

    if(dequals(a,b))
    {
        printf("a==b\n");
    }else{
        printf("a!=b\n");
    }
   if (abs(a - b)<0.0001)
    {
        printf("a==b\n");
    }else{
        printf("a!=b\n");
    }

   // test_float001();
   test_float002();


    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值