c++ - 检查传递的双参数是否为 "close enough"以被视为整数

标签 c++ rounding-error

我正在编写一个代码,我需要在其中检查某个可以采用 double 值的变量是否实际上采用了整数值。如果双变量在整数的容差范围内,我认为它具有整数值。这个公差是 1e-5。

以下是我的代码:

#define SMALL 1e-5
//Double that attains this is considered non zero. Strictly Less than this is 0

int check_if_integer(double arg){
//returns 1 if arg is close enough to an integer
//returns 0 otherwise
    if(arg - (int)arg >= SMALL){
        if(arg + SMALL > (int)(arg+1.0)){
            return(1);
//Code should have reached this point since
//arg + SMALL is 16.00001 
//while (int)(arg+1.0) should be 16
//But the code seems to evaluate (int)(arg+1.0) to be 17
        }
    }
    else{
        return(1);
    }
    return(0);
}

int main(void){

    int a = check_if_integer(15.999999999999998);

}

不幸的是,在传递参数 15.999999999999998 时,函数返回 0。也就是说,它认为参数是小数,而它本应返回 1,表示参数“足够接近”16。

我使用的是 VS2010 专业版。

任何指点将不胜感激!

最佳答案

进一步了解 hvd 关于类型的回答;由于它们的内部表示方式,也不建议在大 double 中添加/减去小 double 。

避免这两个问题的简单解决方法是:

if (abs(arg - round(arg)) <= SMALL) {
  return (1);
} else {
  return (0);
}

关于c++ - 检查传递的双参数是否为 "close enough"以被视为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26778296/

相关文章:

c++ - 将 libpng 与 Borland C++ 链接

c++ - Visual Studio 中的正则表达式捕获组

c++ - 尽管存在 C++ 舍入错误,仍定义范围

C# 舍入 MidpointRounding.ToEven 与 MidpointRounding.AwayFromZero

Excel VBA四舍五入与 double

c++ - Qt:12.625 舍入 2 返回 12.62

c++ - 使 priority_queue 按最小值排序

c++ - std::lock_guard 和 #pragma omp critical 之间的区别

c++ - linux 防止文件描述符在程序退出时关闭

sql - 求和分值问题(处理舍入误差)