c++双精度循环
C++ Looping with doubles
为什么PRINT THIS在下面的代码中从不打印?我已经计算过了<<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;
}
}
}
黄金法则是:在浮点数中避免相等检验。
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;
}
}
}
这可能是由于使用double时的舍入错误,因为0.3实际上并没有在内部完全存储为0.3。
比较双精度数的一种方法是允许在比较中出现一些错误。示例
if(abs(shiftx - shifty) < 0.000001)
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 双精度表示循环加值
- 如何在 for 循环内部或外部打印双精度变量
- 复制地图<双精度,元组<双精度,双精度>>映射<双精度,双精度>没有循环?
- if(a == b) 不适用于 for 循环中的双精度
- 试图在C++中验证双精度有效输入的循环错误
- 使用浮点/双精度作为循环变量
- 为什么我所有的双精度计算都在循环中给出相同的结果
- 在 C 和 C++ 中,for 循环是否可以将双精度值作为索引
- 将字符串转换为双精度值,然后在 While 循环中将其推送到向量
- 为什么我的for循环在双精度向量上崩溃了
- 以双精度数除以双精度数来获得循环中的余数和char参数不起作用
- c++双精度循环
- 为什么这会导致字符而不是双精度的无限循环