簡體   English   中英

Java的Double / Float意外舍入

[英]Java Unexpected Rounding of Double/Float

誰能解釋以下行為? 該方法應該縮放加載的圖片,以使其在不超出范圍的情況下盡可能大。

private final File imageFile;
private final ImageLoaderListener listener;
private final int idealWidth;
private final int idealHeight;
private final float idealRatio;

@Override
protected BufferedImage doInBackground() throws Exception {
    BufferedImage origImage;
    BufferedImage scaledImage;
    int origHeight;
    int origWidth;
    float imgRatio;

    // Load the image.
    try {
        origImage = ImageIO.read( imageFile );
        origHeight = origImage.getHeight();
        origWidth = origImage.getWidth();
        imgRatio = origWidth / origHeight;
        //imgRatio = 5/7;
    } catch (Exception e){
        JOptionPane.showMessageDialog( AppFrame.getAppFrame(),
                "Could not load the image.", "Error Loading Image",
                JOptionPane.ERROR_MESSAGE );
        return null;
    }

    // Scale the image
    double scaleFactor = (imgRatio >= idealRatio) ? idealWidth/origWidth
                                                  : idealHeight/origHeight;
    int scaledWidth = (int) Math.floor( scaleFactor * origWidth );
    int scaledHeight = (int) Math.floor( scaleFactor * origHeight );

    scaledImage = new BufferedImage( scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB );
    AffineTransform at = new AffineTransform();
    at.scale(scaleFactor, scaleFactor);
    AffineTransformOp scaleOp = new AffineTransformOp( 
            at, AffineTransformOp.TYPE_BICUBIC );
    scaledImage = scaleOp.filter(origImage, scaledImage);

    return scaledImage;
}

這是出乎意料的結果:所有除法都是四舍五入而沒有我告訴。 因此,如果我使用idealWidth=1920idealHeight=925運行此idealWidth=1920 ,則調試變量列表將顯示idealHeight = (float) 2.0 同樣,我的測試圖片為532x783,並且imgRatio = (float) 0.0 ScaleFactor在做同樣的事情:532x783圖像導致ScaleFactor = (double) 1.0

當我最初開始對此進行錯誤修正時,我無意中將比率變量( idealRatioimgRatio )聲明為int 我看到了,將它們更改為兩倍,並進行了干凈的構建,以為已修復。 然后在雙打不起作用后將它們更改為浮點數。 現在我很困惑。 為什么在地球上Java仍然會像int

這是標准Java(感謝Daniel,也是大多數靜態類型的語言)的行為。 您在此處執行的操作是整數除法,除非您采取措施防止它返回,否則它將始終返回整數(與除法運算中的值相同的類型)。 您可以將變量設置為float / double,也可以將其強制轉換為float / double,以使除法表達式返回帶有標准舍入的float / double。

好吧,首先, 5/7是一個整數表達式。

(經過簡短的回顧,其他部門顯然也是如此。)

僅供參考,您不能僅將結果分配給double並讓Java執行double precision分割,您需要將每個整數項轉換為double,如下所示:

int x=4;
int y=19;
double z = (double)x/(double)y;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM