问题描述
float num1 = 1;
if (num1 == 1)
{
printf("Yes, it is equal!!\n");
}
else
{
printf("No, it is not equal\n");
}
输出->是的,它是相等的!
output --> Yes, it is equal!
而
float num1 = 1.2;
if (num1 == 1.2)
{
printf("Yes, it is equal!!\n");
}
else
{
printf("No, it is not equal\n");
}
输出->不,不相等
但是为什么呢?请详细说明.
but why?Please explain in detail.
推荐答案
尽管有标题,但没有与任何 int
值进行比较.
In spite of your title, there is no comparison with any int
value.
num == 1.2
将 num
中的 float
值与 1.2的
. double
值进行比较
num == 1.2
compares the float
value in num
with the double
value of 1.2
.
在您的C实现中将 1.2
转换为 double
时,它将转换为最接近的可表示值.由于您的C实现将基于二进制的系统用于浮点运算,因此它不能精确表示1.2,并且转换中会出现小的错误.
When 1.2
is converted to double
in your C implementation, it is converted to the nearest representable value. Since your C implementation uses a binary-based system for floating-point, it cannot exactly represent 1.2, and there is a small error in the conversion.
在 float num1 = 1.2;
中,由 1.2
产生的 double
值再次转换为 float 代码>.由于
float
的精度低于 double
,因此存在更多错误.结果是 float
num1
不等于双精度 1.2
.
In float num1 = 1.2;
, the double
value resulting from 1.2
is converted again, this time to float
. Since float
has less precision than double
, there is even more error. The result is that the float
num1
is not equal to the double 1.2
.
因此,比较 num1 == 1.2
的计算结果为false.
Thus, the comparison num1 == 1.2
evaluates to false.
这篇关于如何在C中将float变量与double进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!