简体   繁体   English

Java浮点数学错误?

[英]Java Floating Point Math Mistake?

I am trying to calculate an aspect ratio for an image: 我正在尝试计算图像的宽高比:

Log.d("img.width:", String.valueOf(img.getIntrinsicWidth()));
Log.d("img.height:", String.valueOf(img.getIntrinsicHeight()));
float aspect = ((float)img.getIntrinsicWidth()) / ((float)img.getIntrinsicWidth());
Log.d("aspect:", String.valueOf(aspect));

however this produces unexpected results: 但这会产生意想不到的结果

img.width:   297
img.height:  167
aspect:      1.0

This seems like it has a simple answer, yet I can't figure it out. 这似乎有一个简单的答案,但我无法弄清楚。

You're dividing width by width. 你将宽度除以宽度。 Try substituting one of them with the height. 尝试用高度替换其中一个。

You have a typo. 你有一个错字。

float aspect = ((float)img.getIntrinsicWidth()) / 
                                                ((float)img.getIntrinsicWidth());

You are dividing the width by the width, which will always produce 1, divide by the height instead: 您将宽度除以宽度,它将始终生成1,除以高度:

float aspect = ((float)img.getIntrinsicWidth()) /
                                               ((float)img.getIntrinsicHeight());

Its a typo, one of them has to be height. 这是一个错字,其中一个必须是高度。 You are dividing width by width 您将宽度除以宽度

float aspect = ((float)img.getIntrinsicWidth()) / ((float)img.getIntrinsicWidth());

你试过float aspect = (new float(img.getIntrinsicWidth())) / (new float(img.getIntrinsicWidth()));

You have a typo, you're dividing width by width. 你有一个错字,你的宽度除以宽度。 Should probably be width by height. 应该是高度宽度。

Also, to make it a bit easier on the eyes, you don't need to cast both sides for a division to use floats; 另外,为了使眼睛更容易,你不需要为了使用花车而将两侧都分开; the left side will be converted to float automatically if the right side is one. 如果右侧是一侧,左侧将自动转换为浮动。

float aspect = img.getIntrinsicWidth() / (float)img.getIntrinsicHeight();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM