考虑以下代码:
#include<stdio.h>
#define k 0.7
#define p 0.5
int main()
{
float a=k,b=p;
double aa=k;
if(a<k)
{
if(b<p) printf("2 is right");
else printf("1 is right");
}
else printf("0 is right");
printf("\n");
if(a>k)
{
if(b<p) printf("2 is right");
else printf("1 is right");
}
else printf("0 is right");
return 0;
}
将此视为该问题的第二部分,这里的理解是浮点常量的双精度值(表示为数字常量时的双精度值)在转换为相应的浮点值时丢失。异常值为 X.5 和 X.0。但我观察到以下结果:
Input Output
K=0.1 to 0.4 0 is right
1 is right
K=0.5 0 is right
1 is right
K=0.6 0 is right
1 is right
K=0.7 1 is right
0 is right
K=0.8 0 is right
1 is right
K=0.9 1 is right
0 is right
K=8.4 1 is right
0 is right
为什么会有这种奇怪的行为?为什么只有少数浮点值显示此属性?我们不能假设float
精度值总是小于精度double
值吗?我们如何解释这种行为?