浮点数字0.1和0.5的精度如何在c中变化

How the precision for floating point numbers 0.1 and 0.5 varies in c

本文关键字:精度 变化 数字      更新时间:2023-10-16

我附加了两个程序。我从门户网站上得到了这些程序。你能解释一下吗?

程序1:

#include<stdio.h>
int main()
{
    float x = 0.4;
    if (x == 0.4)
        printf("n if");
    printf("n sizeof(0.4) : %d sizeof(x) : %d",sizeof(0.4) , sizeof(x));
    return 0;
}

程序2:

#include<stdio.h>
int main()
{
    float x = 0.5;
    if (x == 0.5)
        printf("n if") ;
    printf("n sizeof(0.5) : %d sizeof(x) : %d",sizeof(0.5) , sizeof(x));
    return 0;
}

对于程序1,我得到的输出为:

sizeof(0.4) : 8 sizeof(x) :4

对于程序2,我得到的输出为:

if
sizeof(0.5) : 8 sizeof(x) :4

这两个程序的执行有什么区别?

这不是旧问题的重复。。。。

我需要解释为什么5 的xin倍数的值通过了条件

if(x == 0.4) // here you are comparing float values with double
 printf("n if") ;

所以在这种情况下,隐式类型转换将在内部发生,此时float值将转换为double。(当将浮点值转换为双倍值时,它将为低32位设置0。因此条件失败(

if(x == 0.4f)
 printf("n if") ; // now it will print if

通常情况下,当你给sizeof(0.4)时,它会将0.4视为双倍。对于浮点给出sizeof(0.4f),现在它将给出输出sizeof(0.4): 4