integer division


D

Darius Fatakia

hi,
i'm new to MS Visual Studio and C++ but not to C programming in general. i'm
trying to divide two integers and get their actual quotient (eg 5/3 =
1.666667 etc). i thought i had type cast correctly, but please let me know,
because it appears to be rounding off. my code follows. Thanks!

void DrawLine(GLint x1, GLint y1, GLint x2, GLint y2)

{
int i, pk, dy, dx, yc, xc, inc, temp;
float m;
/*
x1 = 100;
y1 = 200;
x2 = 110;
y2 = 206;
*/

if((x1 >= x2) && (y1 >= y2)) {
temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}

dy = y2 - y1;
dx = x2 - x1;
if (dx != 0) m = (float)(dy/dx);
else m = -999;

// Debugging info
printf("\nDrawLine called!\n");
printf("x1 = %d\n", x1);
printf("y1 = %d\n", y1);
printf("x2 = %d\n", x2);
printf("y2 = %d\n", y2);
printf("dx = %d\n", dx);
printf("dy = %d\n", dy);
if (dx != 0) printf("dy/dx = %d\n", dy/dx);
printf("m = %.2f\n", m);
}

DrawLine called!
x1 = 286
y1 = 204
x2 = 309
y2 = 187
dx = 23
dy = -17
dy/dx = 0
m = 0.00
 
Ad

Advertisements

Ad

Advertisements

H

Howard

Mike Wahler said:
(float)dy / dx;

-Mike

Just to elaborate on WHY Mike's method is required: in the statement
(float)(dy/dx), the results of (dy/dx) are calculated BEFORE the cast to
float, and since dx and dy are integers, that division is done as an integer
division, which drops the fractional part entirely. Casting either of the
values themselves (dy or dy), the division then becomes a floating-point
division because at least one of its parts is floating-point.

-Howard
 

Top