我正在使用 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/