问题描述
或者有没有可能操作会失败?
Or is there a chance that the operation will fail?
谢谢.
我选择了错误的术语,我真正的意思是四舍五入到 0,而不是截断.
I chose the wrong term and what I really meant was rounding to 0, not truncation.
关键是,我需要比较两个双精度的整数部分,我只是将它们转换为 int,然后使用 ==,但是,正如有人在我之前的一个问题中指出的那样,这可能会引发溢出如果双精度不能放入整数,则异常.
The point is, I need to compare the integer part of two doubles and I'm just casting them to int and then using ==, but, as someone pointed out in one of my earlier questions, this could throw an overflow exception if the double can't fit into the integer.
所以问题是'使用 == 运算符比较两个先前舍入为 0 的双精度值是否正确,或者我应该坚持转换为 int 方法并捕获可能的异常?
So the question would be 'Is it correct to use the == operator to compare two doubles that have previously been rounded to 0, or should I stick to the casting to int method and catch a possible exception?
推荐答案
这里是更新的站点,其中讨论了比较浮点数的几种方法的优缺点.(您仍然可以在此处查看 旧网站.)
Here's the updated site which discusses the pros and cons of several methods of comparing floating point numbers. (You can still view the old site here.)
我要采用的方法是相对误差"方法.找出两个数字之间的差异,将其转换为数字的百分比,如果该百分比足够小,那么您就得到了相等.
The method I'd go with is the "relative error" method. Find the difference between the two numbers, convert that to a percentage of the numbers, and if that percentage is sufficiently small, then you've got equality.
这篇关于使用 == 运算符比较两个舍入浮点数是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!