【问题标题】:How can I round down to the nearest integer from an int array?如何从 int 数组向下舍入到最接近的整数?
【发布时间】:2012-01-26 15:02:32
【问题描述】:

我正在用 Java 设计一个捐赠插件,用户可以从中捐赠自定义金额。通过捐赠,您可以从某些包裹中获得好处。

我想做的,是将整数n向下取整到最近的捐赠包。

例如,可能有 3 个捐赠包,全部以整数表示。有 5 美元、10 美元和 20 美元的捐款包。如果用户捐赠 13 美元,我希望插件将其四舍五入到 10 美元,因为这是最近的捐赠包。

【问题讨论】:

  • 你真的是指“选择小于等于n的最大捐款金额”吗?
  • 是的,我确实想这样做

标签: java arrays math integer rounding


【解决方案1】:

好吧,我今天有一些空闲时间。 (: 关心捐赠数组的顺序是递增的.. 否则先排序

public class Donation {
    private static int[] donArray = {10, 5, 30, 20};
    static{
        Arrays.sort(donArray);
    }

    public static void main(String[] args){
        int paid = 13;
        System.out.println("Applied Donation: " + applyDonation(paid));
    }

    private static int applyDonation(int paid) {
        int applied = 0;
        for(int range: donArray){
            if(range <= paid)
                applied = range;
            else
                break;
        }
        return applied;
    }
}

甚至更简单:

    TreeSet<Integer> donSet = new TreeSet<Integer>(Arrays.asList(new Integer[]{10, 5, 30, 20}));
    int paid = 13;
    System.out.println("Applied Donation: " + donSet.floor(paid));

【讨论】:

  • +1 - 我写答案时不知道 floor() 。它还不必检查 NoSuchElementException。您的第二个答案无疑是最好的答案。
【解决方案2】:

将所有值放入TreeSet&lt;Integer&gt;,然后使用

myTreeSet.headSet( donatedValue ).last();

【讨论】:

    【解决方案3】:

    您可以对捐赠数组使用二进制搜索并找到新捐赠值所在的索引,然后使用 if-else 轻松地从这两个值中做出决定。
    编辑:您需要事先对数组进行排序。

    【讨论】:

      【解决方案4】:

      尝试将其除以 10,四舍五入到最接近的整数,然后再乘以 10。

      例如。

      13/10=1.3 -> 1.3~1 -> 1*10 = 10$
      

      16/10=1.6 -> 1.6~2 -> 2*10=20$
      

      当然这只适用于10s的捐赠包。

      【讨论】:

        【解决方案5】:

        我不知道为什么不是这个?

        if(donation >10 && <=15) {           //say you want to round 15 or less to 10
          donation=10;
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多