金额随机分配

面试–机试–随机分配金额

遇到过的面试题,记录一下

public class demo {

public static void main(String[] args) {
//分成几个
int count = 3;
//总金额
double amount = 10;
//最小金额
double singleMin = 0.01;
//最大金额
double singleMax = 10.00;
double money = 0;
for (int i = 0, len = count; i < len; i++) {
//模拟3个人分
  money = test(count--, amount -= money, singleMin, singleMax);
    System.out.println("第"+(i+1)+" 份为"+money);
}

}

/**
* @param count 分配个数
* @param amount 分配总金额
* @param singleMin 单份最小金额
* @param singleMax 单份最大金额
*/
private static double test(int count, double amount, double singleMin, double singleMax) throws UnsupportedOperationException {
if (amount > singleMax || amount < singleMin) {
throw new UnsupportedOperationException(String.format(“金额不能大于%s,不能小于%s”, singleMax, singleMin));
}
if (count * singleMin > amount) {
throw new UnsupportedOperationException(String.format(“金额不足够发%s个”, count));
}

if (count == 1) {
//剩余最后一个
  return (double) Math.round(amount * 100) / 100;
}
//当前的最小金额
double min = 0.01;
//当前的最大金额
double max = amount / count * 2;
//金额
double money = new Random().nextDouble() * max;
//特殊处理,保留2位小数,四舍五入
money = money <= min ? min : Math.floor(money * 100) / 100;
return money;

}
}
复制后直接使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值