简体   繁体   中英

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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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