gpt4 book ai didi

c++ - float 0.1 和 0.5 的精度在 c 中如何变化

转载 作者:行者123 更新时间:2023-11-30 21:30:37 26 4
gpt4 key购买 nike

我附上了两个程序。我从门户网站获取了这些程序。您能解释一下吗?

程序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

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

这不是旧发布问题的重复......

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

最佳答案

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

因此在这种情况下,隐式类型转换将在内部发生,此时 float 值将转换为 double。(将 float 值转换为 double 时,它​​将为低 32 位添加 0。因此条件失败)

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

通常,当您给出 sizeof(0.4) 时,它会将 0.4 视为 double。对于 float 给出 sizeof(0.4f),现在它将给出输出 sizeof(0.4): 4

关于c++ - float 0.1 和 0.5 的精度在 c 中如何变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24927056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com