This question already has answers here:
strange output in comparison of float with float literal
                                
                                    (8个答案)
                                
                        
                                4年前关闭。
            
                    
我正在使用C并尝试过:-

#include<stdio.h>
int main()
{
     float b=0.8,a=0.6;
     if(a&&b>=0.8)
     printf("\nclass")  ;
     else
     printf("\nb");
     return 0;
}


输出是:-

class


但是当我将b的值更改为0.9并将if的表达式更改为a && b> = 0.9时:

#include<stdio.h>
int main()
{
     float b=0.9,a=0.6;
     if(a&&b>=0.9)
     printf("\nclass")  ;
     else
     printf("\nb");
     return 0;
}


然后输出是:

b


谁能解释为什么当b值为0.9时> =运算符开始充当>运算符吗?

提前致谢。

有些人认为我在浪费他们的时间会增加一些东西:
我也尝试将其调试为:-

    #include<stdio.h>
int main()
{
float b=0.9,a=0.6;
printf(" int a   -   %d\n", (int)a);
printf("int b -    %d\n", (int)b);
printf("a&&b  -   %d\n", a&&b);
printf("b>=0.9  -  %d\n", b>=0.9);
if(a&&b>=0.9)
printf("\nclass");
else
printf("\nb");
return 0;
}


现在O / p是:

int a   -   0
int b -    0
a&&b  -   1
b>=0.9  -  0


现在,请“优先人员”告诉我在单个> =运算符中将遵循什么优先顺序。

最佳答案

您的代码等效于:

double x1 = 0.9;
float xf = (float)x1; // discard some precision
double x2 = (double)xf;

if (x2 >= x1) {
    // ...
}


问题是,在通过将x1转换为float而放弃了double的某些精度之后,就永远无法恢复它。将其投射回x2不会恢复该精度。因此0.9仍然与不同,并且由于四舍五入的方向,它恰好少了一些。 (注意:如果您尝试使用其他值进行相同的操作,则有时会发现更多内容。)

关于c - 与0.9相比,为什么> =运算符在C中用作>运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32682155/

10-09 08:30
查看更多