我对此很困惑......这是我的代码的摘录......
float m = 0.0, c = 0.0;
printf("toprightx = %d bottomrightx = %d toprighty = %d bottomrighty = %d\n",
toprightx, bottomrightx, toprighty, bottomrighty);
// find m and c for symmetry line
if (toprightx == bottomrightx) {
m = (-toprighty + bottomrighty);
}
else {
m = (-toprighty + bottomrighty) / (toprightx - bottomrightx);
}
c = -toprighty - (m * toprightx);
printf("m = %f and c = %f\n", m, c);
这是输出:
toprightx = 241 bottomrightx = 279 toprighty = 174 bottomrighty = 321
m = -3.000000 and c = 549.000000
为什么输出四舍五入 m 和 c?我已将它们声明为 float ,所以我不明白为什么代码返回整数。 m的正确值应该是-3.8684。
(请注意,toprightx、bottomrightx、toprighty、bottomrighty 已在代码中进一步声明为整数。)
最佳答案
Note that toprightx, bottomrightx, toprighty, bottomrighty have been declared as integers further up in the code.
这就是你的答案。仅涉及整数的计算在整数数学中执行,包括除法。然后将结果分配给 float 并不重要。
要解决此问题,请将至少一个 x/y 值声明为 float 或在计算中将其强制转换为 float 。
关于c++ - float 在 C++ 中四舍五入,我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6726995/