如何在C中比较浮点变量和双精度? [英] How to compare float variable with double in C?
问题描述
float num1 = 1;
if (num1 == 1)
{
printf("Yes, it is equal!!
");
}
else
{
printf("No, it is not equal
");
}
输出 --> 是的,它是相等的!
output --> Yes, it is equal!
而
float num1 = 1.2;
if (num1 == 1.2)
{
printf("Yes, it is equal!!
");
}
else
{
printf("No, it is not equal
");
}
输出 --> 不,不等于
output --> No, it is not equal
但是为什么呢?请详细说明.
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
.
当 1.2
在您的 C 实现中转换为 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
不等于 double 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中比较浮点变量和双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!