我正在编写一个代码,我需要在其中检查某个可以采用 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/