浮点数在C++中被舍入,我不明白为什么

And*_*rew 4 c++ floating-point types integer

我对此非常困惑......这是我的代码摘录..

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);
Run Code Online (Sandbox Code Playgroud)

这是输出:

toprightx = 241 bottomrightx = 279 toprighty = 174 bottomrighty = 321
m = -3.000000 and c = 549.000000
Run Code Online (Sandbox Code Playgroud)

为什么输出舍入m和c?我已将它们声明为浮点数,因此我不明白为什么代码返回整数.m的正确值应为-3.8684.

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

Mic*_*rdt 14

请注意,toprightx,bottomrightx,toprighty,bottomrighty已在代码中进一步声明为整数.

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

要解决这个问题,要么将至少一个x/y值声明为float,要么将其转换为浮动计算.


Pau*_*aul 7

您正在此行执行整数除法:

(-toprighty + bottomrighty) / (toprightx - bottomrightx);
Run Code Online (Sandbox Code Playgroud)

由于topright,bottomrighty,toprightx和bottomrightx都是整数,因此该等式的结果也将是整数.等式计算完整数后,您将其分配给浮点数.它相当于:

float m = -3;

你可以这样做:

(-toprighty + bottomrighty + 0.0) / (toprightx - bottomrightx);
Run Code Online (Sandbox Code Playgroud)


Set*_*son 5

这是int给你的啊:

m = (-toprighty + bottomrighty) / (toprightx - bottomrightx);
       ^int        ^int              ^int        ^int
Run Code Online (Sandbox Code Playgroud)

所有这些操作都将使用整数除法(截断浮点)然后转换为float.尝试改为:

m = float(-toprighty + bottomrighty) / (toprightx - bottomrightx);
Run Code Online (Sandbox Code Playgroud)

  • h`int`为+1,对分子使用强制转换.分母上的演员也有效,但演员表隐藏在代码的人类读者身上.抛出分子使得即使是偶然的读者也明显看出需要浮点结果. (2认同)