面试–机试–随机分配金额
遇到过的面试题,记录一下
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;
}
}
复制后直接使用