为什么下面代码中的PRINT THIS从不打印?我已经引用了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; } }} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 黄金法则是:避免在浮点中进行相等性测试。0.1和0.3都不能精确表示。标准阅读:What Every Computer Scientist Should Know About Floating-Point Arithmetic。为了解决您的特定问题,您应该使用整数类型进行迭代并执行比较。仅在实际需要时才转换为浮点类型。例如。: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; } }} (adsbygoogle = window.adsbygoogle || []).push({}); 09-16 19:00