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

后端 未结 4 1020
心在旅途
心在旅途 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: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
    
    0 讨论(0)
  • 2021-01-28 13:46

    If you're talking about this GameContainer class, getWidth() and getHeight() return an int.

    So you have to cast it as double

    scaleFactorWidth = (double)2880 / ui.getWidth();
    scaleFactorHeight = (double)1800 / ui.getHeight();
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-01-28 13:52

    Cast it to Double.

       scaleFactorWidth = (Double)2880 / ui.getWidth();
        scaleFactorHeight = (Double)1800 / ui.getHeight();
    
    0 讨论(0)
提交回复
热议问题