此类包含矩形列表,我需要找到面积最小的矩形。
我发现需要按面积比较矩形,但它具有 double 。 我知道我的比较记得最后一个,但是我们如何在这里进行此检查?
代码:
/**
* Gets the Rectangle with the smallest area
* @return the rectangle with the smallest area or null if
* there are no rectangles
*/
public Rectangle smallestArea()
{
if (list.size() == 0) return null;
Rectangle smallest = list.get(0);
double smallestArea = smallest.getWidth() * smallest.getHeight();
for (int i = 1; i < list.size(); i++) {
Rectangle next = list.get(i);
double nextArea = next.getWidth() * next.getHeight();
if ((nextArea - smallestArea) < 0) smallest = next;
}
return smallest;
}
如何解决这个问题?
最佳答案
您还应该更新 smallestArea
局部变量(代码中多一行):
public Rectangle smallestArea()
{
if (list.size() == 0) return null;
Rectangle smallest = list.get(0);
double smallestArea = smallest.getWidth() * smallest.getHeight();
for (int i = 1; i < list.size(); i++) {
Rectangle next = list.get(i);
double nextArea = next.getWidth() * next.getHeight();
if ((nextArea - smallestArea) < 0) {
smallest = next; // <- Whenever you've updated smallest
smallestArea = nextArea; // <- Do not forget updating the smallestArea as well
}
}
return smallest;
}
关于java - 如何比较两个双数并找到较小的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18526982/