如何在C中比较浮点变量和双精度? [英] How to compare float variable with double in C?

查看:38
本文介绍了如何在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.2num 中的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆