c++ - float 在 C++ 中四舍五入,我不明白为什么

标签 c++ types floating-point 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);

这是输出:

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/

相关文章:

Java - System.out.printf 舍入 float

Python float 到字符串 : how to get '0.03' but '-.03'

具有类键和类值的 C++ STL 映射容器

c++ - 为什么我的程序这么慢?

c++ - 关闭顺序

haskell - 容器元素类型

php - 在 MySQL 数据库中存储纬度和经度值的问题

c++ - shared_ptr 到数组

java - 在 Java 中返回一个值

c++ - 当 cin 需要 int 时检测 char