为int而用C浮动可能直接关系之间的比较? [英] Is relational comparison between int and float directly possible in C?

查看:110
本文介绍了为int而用C浮动可能直接关系之间的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Visual Studio 6用C语言编写的一些旧时代的code。我发现那里的code看起来像这样的问题。

I am using Visual Studio 6 with some old time code written in c. I found an issue where the code looks like this..

int x = 3;
float y = 3.0;

if(x == y){
   do some crazy stuff
}

这是一个有效的比较?是否有可能在运行时为浮动分配是3.0000001,这会失败?

is this a valid comparison? is it possible at run time the allocation for the float is 3.0000001 and this would fail?

推荐答案

好吧,我想你也不会太surpised听到相等比较彩车是一个新手的错误呢。

Well, I guess you won't be too surpised to hear that comparing floats for equality is a rookie mistake then.

的问题是,许多的增量小于一个整数值实际上不能重新$ P $在IEEE浮点恰好psented。所以,如果你试图通过指数,它高达3.0的值到达浮动(比如增量为0.1),这是很有可能的平等比较可以的从不的是真实的。

The problem is that many increments smaller than an integer values can't actually be represented exactly in IEEE floating point. So if you arrive at the float by trying to "index" it up to the value of 3.0 (say in increments of 0.1), it is quite possible your equality comparison can never be true.

这也是刚刚从类型强度的角度来看是一个坏主意。您应该浮动转换成一个int,请检查您的INT是足够接近(例如:< 3.1和> 2.9或诸如此类),或者更好,如果你正试图使浮球的东西就像一个做双重责任计数器,避免了整体思路。

It is also a bad idea just from a type-strength standpoint. You should either convert the float into an int, check for your int being "close enough" (eg < 3.1 and > 2.9 or somesuch), or better yet if you are trying to make that float do double-duty for something like a counter, avoid the whole idea.

这篇关于为int而用C浮动可能直接关系之间的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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