【问题标题】:Floats being rounded in C++ and I don't understand why浮点数在 C++ 中四舍五入,我不明白为什么
【发布时间】:2011-10-07 07:21:22
【问题描述】:

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

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 已在代码中进一步声明为整数。)

【问题讨论】:

  • 我不是 C 程序员,但我很确定它首先进行整数数学运算(由于使用了变量)并将结果填充到浮点数中。您需要将其他变量定义为浮点数。
  • 为什么'toprightx,bottomrightx'会有所不同?如果 'toprightx' 少,不应该是 'topleftx' [或只是 'left']?
  • @PaulPRO:你为什么要提供赏金?你在这里找什么?

标签: c++ types floating-point integer


【解决方案1】:

那是因为您在计算中仅使用 int,因此 C++ 使用整数计算。只需将您的 int 变量之一转换为 float 即可。

将此语句 m = (-toprighty + bottomrighty) / (toprightx - bottomrightx); 更改为 m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx); 即可。

【讨论】:

    【解决方案2】:

    这是给你的 hint

    m = (-toprighty + bottomrighty) / (toprightx - bottomrightx);
           ^int        ^int              ^int        ^int
    

    所有这些操作都将使用整数除法(截断浮点数)执行,然后转换为float。试试吧:

    m = float(-toprighty + bottomrighty) / (toprightx - bottomrightx);
    

    【讨论】:

    • +1 表示 h int,以及在分子上使用强制转换。分母上的演员表也有效,但该演员表对代码的人类读者是隐藏的。转换分子使得即使是普通读者也很明显需要浮点结果。
    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      将浮点数转换为 int 会截断不适合新类型的数据。

      请注意,您的数据也没有被四舍五入,而是被截断。

      【讨论】:

        【解决方案5】:

        尝试将除数转换为浮点数,强制除法使用浮点运算:

        m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx);
        

        【讨论】:

        • 如果你只打算投分子或分母之一,最好投分子。为什么要对人类读者隐藏该演员表?
        【解决方案6】:

        在请求混合算术之前将 toprightx、bottomrightx、toprighty、bottomrighty 声明为浮点数或将它们转换为浮点数。

        【讨论】:

          【解决方案7】:

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

          (-toprighty + bottomrighty) / (toprightx - bottomrightx);
          

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

          float m = -3;

          你可以这样做:

          (-toprighty + bottomrighty + 0.0) / (toprightx - bottomrightx);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-27
            • 1970-01-01
            相关资源
            最近更新 更多