Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am very confused about this... Here is an extract from my code..

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

And here is the output:

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

Why is the output rounding m and c? I have declared them as floats so I don't understand why the code is returning integers. The correct value of m should be -3.8684.

(Note that toprightx, bottomrightx, toprighty, bottomrighty have been declared as integers further up in the code.)

like image 227
Andrew Avatar asked Nov 27 '22 03:11

Andrew


1 Answers

Note that toprightx, bottomrightx, toprighty, bottomrighty have been declared as integers further up in the code.

There's your answer. Calculations that involve only integers are performed in integer math, including divisions. It doesn't matter that the result is then assigned to a float.

To fix this, either declare at least one of the x/y values as float or cast it to float in the calculation.

like image 90
Michael Borgwardt Avatar answered Dec 10 '22 12:12

Michael Borgwardt