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

后端 未结 4 1021
心在旅途
心在旅途 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条回答
  •  梦毁少年i
    2021-01-28 13:32

    ui.getWidth and ui.getHeight() returns you int and when you are performing operation on int it returns you int again. So convert your int value to Double.

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

    Check below sample,

    public static void main(String[] args) {
                Double scaleFactorWidth =  new Double(2880) /  new Double(1024);
                Double scaleFactorHeight = new Double(1024) / new Double(600);
    
    
                System.out.println("Scale factors are: "
                        + Double.toString(scaleFactorWidth) + " "
                        + Double.toString(scaleFactorHeight));
    
                Double textScale = (scaleFactorWidth + scaleFactorHeight) / 2;
    
                System.out.println("Text scale is: " + Double.toString(textScale));
            }
    

    output:

    Scale factors are: 2.8125 1.7066666666666668
    Text scale is: 2.2595833333333335
    

提交回复
热议问题