我对此很困惑...这是我的代码的一部分。

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?我已经将它们声明为浮点数,所以我不明白为什么代码返回整数。 m的正确值应为-3.8684。

(请注意,toprightx,bottomrightx,toprighty,bottomrighty已在代码中声明为整数。)

最佳答案



有你的答案。仅涉及整数的计算是在包括除法在内的整数数学中执行的。然后将结果分配给浮点数并不重要。

要解决此问题,请在计算中将至少一个x/y值声明为float或将其强制转换为float。

10-01 21:46