繁体   English   中英

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

[英]Floats being rounded in C++ and I don't understand why

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

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);

这是 output:

toprightx = 241 bottomrightx = 279 toprighty = 174 bottomrighty = 321
m = -3.000000 and c = 549.000000

为什么 output 舍入 m 和 c? 我已将它们声明为浮点数,所以我不明白为什么代码返回整数。 m 的正确值应该是 -3.8684。

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

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

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

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

您正在这条线上执行 integer 除法:

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

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

float m = -3;

你可以这样做:

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

这是给你的 ah int

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

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

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

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

更改此语句m = (-toprighty + bottomrighty) / (toprightx - bottomrightx); m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx); 会这样做。

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

将浮点数转换为 int (隐含地,就像你正在做的那样)将截断不适合新类型的数据。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM