And*_*drw 1 c++ double comparison loops
为什么PRINT THIS在下面的代码中从不打印?我已经cout << shiftx和shifty确保在某些时候,它们都是0.3.
for(double shifty=0; shifty < 2; shifty+=.1) {
for(double shiftx=0; shiftx < 2; shiftx +=.1) {
if((shiftx == 0.3) && (shifty == 0.3)) {
cout << "PRINT THIS" << endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)
黄金法则是:避免在浮点数中进行相等性测试.
0.1和0.3都不能精确表示.
标准阅读:每个计算机科学家应该知道的浮点运算.
要解决您的特定问题,您应该使用整数类型进行迭代并执行比较.实际需要时只转换为浮点类型.例如:
for(int shifty=0; shifty < 20; shifty++) {
for(int shiftx=0; shiftx < 20; shiftx++) {
double shifty_double = shifty * 0.1;
double shiftx_double = shiftx * 0.1;
if((shiftx == 3) && (shifty == 3)) {
cout << "PRINT THIS" << endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)