Fixing this code to avoid the rounding warning when compiling

ChuckieAJ 66 Reputation points


Take this code:

rectDraw.SetRect(0, 0, rectDraw.right, rectDraw.right / nRatioImage);

nRatioImage is of tale float. And the others are of type int.

At the moment I get a compile warning:

warning C4244: 'argument': conversion from 'float' to 'int', possible loss of data

I tried to adjust the line like this:

rectDraw.SetRect(0, 0, rectDraw.right, rectDraw.right / (int)nRatioImage);

But it yields the wrong results. What is the right way to use a cast with this line of code? I have a similar line here:

rectDraw.SetRect(0, 0, rectDraw.bottom * nRatioImage, rectDraw.bottom);

Thank you.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,441 questions
0 comments No comments
{count} votes

Accepted answer
  1. Guido Franzke 2,201 Reputation points

    be aware that a division/multiplication with a float will result in a float. If you cast the result to int, the value will be truncated. Use rounding functions like floor, ceil or so.

    But if you only want to get rid of the warning, use this for example:

    rectDraw.SetRect(0, 0, rectDraw.right, (int)(rectDraw.right / nRatioImage));
    rectDraw.SetRect(0, 0, (int)(rectDraw.bottom * nRatioImage), rectDraw.bottom);

    It will truncate the float result to int according to the compiler settings (normally without rounding).
    Regards, Guido

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful