为什么不能比较浮点数? [英] Why Floating point numbers cant be compared?

查看:158
本文介绍了为什么不能比较浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在float与float文字比较中的奇怪输出

Possible Duplicate:
strange output in comparision of float with float literal

#include<stdio.h>
int main()
{
float me = 1.7;
if(me==1.7)
   printf("C");
else
   printf("C++");
}

Output: C++

现在,这种现象的原因是,许多浮点数不能用二进制绝对精度表示.

Now the reason for this behaviour is said that many floating point numbers cant be represented with absolute precision in binary.

我的问题是-如果计算机以二进制方式思考和操作.比较时,me的任何不保证对于1.7都是相同的.所以两者应该相等.

My question is that - If computer thinks and manipulates in binary. Any uncertanity in representation of me would be same for 1.7 when compared. So both should be equal.

那么类型转换如何解决这个问题呢? (float)1.7

ALso how typecasting solves this problem? (float)1.7

推荐答案

您正在将浮点数与双精度数进行比较.文字1.7是双精度型.

You are comparing a float to a double. the literal 1.7 is a double.

您已将其存储在浮点数中,其精度可能不及双精度数,因此me == 1.7会将1.7作为浮点数(提升为double)与1.7作为double进行比较.

You've stored that in a float, which might have less precision than a double, thus the me == 1.7 is comparing 1.7 as a float(promoted to a double) to 1.7 as a double.

在这种情况下,me == 1.7f应该使它们比较相等,或者将me更改为双精度double me = 1.7;

In this case, me == 1.7f should make them compare as equal, or changing me to a double double me = 1.7;

在一般情况下,您希望使用@duffymo显示的epsilon比较相等性.

In the general case though, you'd want equality to be compared using an epsilon as @duffymo shows.

此外,必读.

这篇关于为什么不能比较浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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