integer division

Discussion in 'C++' started by Darius Fatakia, Jan 28, 2004.

  1. 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
     
    Darius Fatakia, Jan 28, 2004
    #1
    1. Advertisements

  2. Darius Fatakia

    Mike Wahler Guest

    (float)dy / dx;

    -Mike
     
    Mike Wahler, Jan 28, 2004
    #2
    1. Advertisements

  3. Darius Fatakia

    Howard Guest

    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
     
    Howard, Jan 28, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.