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

I am very confused by this ... Here is an excerpt 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 conclusion:

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

Why rounding output m and c? I declared them floating, so I don’t understand why the code returns integers. The correct m value should be -3.8684.

(Note that toprightx, bottomrightx, toprighty, bottomrighty are declared as integers in the code.)

+4
source share
7 answers

Note that toprightx, bottomrightx, toprighty, rightrighty were declared integers later in the code.

Here is your answer. Calculations that include only integers are performed in integer math, including divisions. It does not matter that the result is then assigned to a floating point.

To fix this, declare at least one of the x / y values ​​as a float or run it for calculation in the calculation.

+14
source

You do integer division on this line:

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

Since topright, rightright, toprightx and bottomrightx are integers, the result of this equation will also be an integer. After equaition calculates an integer, you assign its float. This is equivalent to:

float m = -3;

Instead, you can do something like this:

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

Here's the h int for you:

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

All these operations will be performed using integer division (floating point trimming), and then discarded by float . Try instead:

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

This is because you use only int for your calculations, therefore C ++ uses integer calculation for them. Just drop one of your int variables to swim, and you will be fine.

Change this expression m = (-toprighty + bottomrighty) / (toprightx - bottomrightx); to m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx); will do it.

+3
source

declare toprightx, rightrightx, toprighty, rightrighty as a float or drop them to a float before requesting mixed arithmetic.

+2
source

Casting (implicitly how you do it), float to int will clip data that will not fit into the new type.

Please note that your data is also not rounded, it is truncated.

+2
source

Try distinguishing the divisor from a floating point number to force the division to use floating point arithmetic:

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

All Articles