Java rounding the results of a division when it shouldn't be

后端 未结 4 1082
心在旅途
心在旅途 2021-01-28 12:55

So I have some code for scaling graphics to the size of a users screen by dividing the size of an \'Ideal\' screen by the size of the users screen. Hers is a code snippet of wha

4条回答
  •  忘掉有多难
    2021-01-28 13:51

    In these lines

    scaleFactorWidth = 2880 / ui.getWidth();
    scaleFactorHeight = 1800 / ui.getHeight();
    

    The calculation itself is Integer-based (according to the later calls of Integer.toString()). Just the result is then casted to double.

    Use this code instead, in order to have the actual computation use double values:

    scaleFactorWidth = 2880.0 / ui.getWidth();
    scaleFactorHeight = 1800.0 / ui.getHeight();
    

    or

    scaleFactorWidth = 2880.0 / (double)ui.getWidth();
    scaleFactorHeight = 1800.0 / (double)ui.getHeight();
    

提交回复
热议问题