在我的代码中,我现在得到了一个元素列表以循环遍历并计算一些值:
double targetRatio = Math.min((double)w/h, (double)h/w);//height & width of the screen
List<Size> sizes //populated with supported height and width
double ratioArray[];
int i;
for (i = 0; i <= sizes.size(); i++)
{
double ratio = Math.min((double)sizes.get(i).width/sizes.get(i).height, (double)sizes.get(i).height/sizes.get(i).width);
ratioArray[i] = Math.abs(ratio - targetRatio);
// Math.min((double)sizes.get(i).width/w, (double)w/sizes.get(i).width);
// Math.min((double)h/sizes.get(i).height, (double)sizes.get(i).height/h);
//sizes.get(i).width
//sizes.get(i).height
}
ratioArray [i]中的值越低,我得到的比率就越好;现在我被困在寻找最佳比率时,我可以这样做:
Arrays.sort(ratioArray);
但是那我该如何找回索引呢?我必须使最小值指向它的大小
最佳答案
最好的方法是遍历ratioArray并且不要使用Arrays.sort(ratioArray);
double targetRatio = Math.min((double)w/h, (double)h/w);//height & width of the screen
List<Size> sizes //populated with supported height and width
double ratioArray[];
int i;
for (i = 0; i <= sizes.size(); i++)
{
double ratio = Math.min((double)sizes.get(i).width/sizes.get(i).height, (double)sizes.get(i).height/sizes.get(i).width);
ratioArray[i] = Math.abs(ratio - targetRatio);
// Math.min((double)sizes.get(i).width/w, (double)w/sizes.get(i).width);
// Math.min((double)h/sizes.get(i).height, (double)sizes.get(i).height/h);
//sizes.get(i).width
//sizes.get(i).height
}
在上面的代码之后,
int min = ratioArray[0];
int minindex;
for (int i = 0; i < ratioArray.length; i++) {
if(min > ratioArray[i]) {
min = ratioArray[i];
minindex = i;
}
}
你会得到你的minindex