gpt4 book ai didi

Java Double/Float 的意外舍入

转载 作者:行者123 更新时间:2023-11-29 10:06:15 24 4
gpt4 key购买 nike

任何人都可以解释以下行为吗?此方法应该缩放加载的图片,使其在一定范围内尽可能大而不会越过。

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 运行它,调试变量列表将显示 idealHeight = (float) 2.0。同样,我的测试图片是 532x783,imgRatio = (float) 0.0。 ScaleFactor 做同样的事情:532x783 图像产生 ScaleFactor = (double) 1.0

当我最初开始修复此错误时,我无意中将比率变量(idealRatioimgRatio)声明为 int。我看到了这个,将它们更改为 double ,并做了一个干净的构建,认为它是固定的。然后我在 double 不起作用后将它们改为花车。现在我被难住了。为什么 Java 仍然像 int 一样运行?

最佳答案

这是标准的 Java(也是大多数静态类型语言,感谢 Daniel)的行为。你在这里做的是整数除法,它将始终返回一个整数(与除法运算中的值类型相同),除非你采取措施防止它。您可以将变量转换为 float / double 或将一个变量转换为 float / double ,以使除法表达式返回带标准舍入的 float / double 。

关于Java Double/Float 的意外舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7364231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com