java - 如何比较两个双数并找到较小的

标签 java compare double rectangles

此类包含矩形列表,我需要找到面积最小的矩形。

我发现需要按面积比较矩形,但它具有 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/

相关文章:

.net - 比较两个非整数的整数部分的最佳方法是什么?

java - Android CPU : double, 整数我如何计算有关系吗?在特定情况下什么更快?

java - 如何分隔java字符串的各个部分?

delphi - 比较大文件

java - OpenCSV - 如何将选定的列映射到 Java Bean 而不管顺序如何?

java - Spring Boot 测试 - MockHttpServletResponse getContentLength 返回 0 尽管有内容

java - 无法从 CursorWindow 读取第 34 行第 11 列

python - 检查字符串的任何字符是否在列表中

java - 如何从 10.0/3*3 BigDecimal 和 double 得到?

java - 我如何使用来自 Kotlin 的不可空元素的 Java 集合?