Dividing by two integers does not return expected result

前端 未结 6 601
甜味超标
甜味超标 2021-01-25 13:18

I\'m currently writing a program that requires a preview of a live display, but the preview, of course, is scaled down. However, when I scale the PictureBox down, t

6条回答
  •  后悔当初
    2021-01-25 13:22

    You are doing integer division.

    what you need to do is this :

    private void FindOptimalRes(PictureBox picBox)
    {
        double h = Height / 4D; // or Height / 4.0
        double ratio = 4D / 3D; // or 4.0 / 3.0
        picBox.Size = new Size((int)(h * ratio), (int)h); // Size is now correct [133,100]
    }
    

    when you do a mathematical operation with an integer literal (no decimal places) it is implicitly typed as an int.

    Simply appending a capital D at the end of your literals (4D, 3D) will type them as doubles, and your math will be correct. Alternatively you can write 4.0, 3.0

提交回复
热议问题