C语言中的浮点错误
当使用相等运算符使值相等时,输出显示失败而不是成功。这是编译器版本的问题吗?附加程序的屏幕截图 看看这个: 预测以下C程序的输出C语言中的浮点错误,c,C,当使用相等运算符使值相等时,输出显示失败而不是成功。这是编译器版本的问题吗?附加程序的屏幕截图 看看这个: 预测以下C程序的输出 #include<stdio.h> int main() { float x = 0.1; if (x == 0.1) printf("IF"); else if (x == 0.1f) printf("ELSE IF"); else printf("ELSE"); } The
#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
printf("IF");
else if (x == 0.1f)
printf("ELSE IF");
else
printf("ELSE");
}
The output of above program is “ELSE IF” which means the expression “x == 0.1” returns false and expression “x == 0.1f” returns true.
#包括
int main()
{
浮动x=0.1;
如果(x==0.1)
printf(“如果”);
否则如果(x==0.1f)
printf(“其他如果”);
其他的
printf(“其他”);
}
上述程序的输出为“ELSE IF”,表示表达式“x==0.1”返回false,表达式“x==0.1f”返回true。
摘自询问前,请查阅C信息页面!不要发布文本图像!您应该始终假设不可能比较浮点数是否相等。与0.1比较不起作用的原因是0.1是双精度的,并且与k不是同一个数字,因为k是一个浮点数,并且在其表示形式中具有较少的有效数字。您可以比较浮点数是否相等,但前提是两个值的赋值方式完全相同。但这通常很少见,因此最好将其差值的绝对值与较小的正值进行比较,以确定它们是否“足够接近”,从而被视为相等。
#include<stdio.h>
int main()
{
float x = 0.1;
if (x == 0.1)
printf("IF");
else if (x == 0.1f)
printf("ELSE IF");
else
printf("ELSE");
}
The output of above program is “ELSE IF” which means the expression “x == 0.1” returns false and expression “x == 0.1f” returns true.