题目:定义抢红包的方法fighting,用户输入总金额total和红包的个数,输出每个红包获得的金额。
红包的基本算法
a) 必须每个人都能获得一定额度的金额设定一个最小值 0.01
b) 最大值=平均金额的两倍
c) 平均金额:总金额-已经被拿走的金额/剩余的人数
public class RedEnvelope {
public static void fighting() {
Random rand = new Random();
//单个红包的最小金额为0.01
double min = 0.01;
Scanner sc = new Scanner(System.in);
System.out.println("请输入红包的总金额:");
double total = sc.nextDouble();
System.out.println("请输入红包的个数:");
int num = sc.nextInt();
if (num == 1) {
System.out.println(total);
}
//剩余金额
double rest = total;
double[] money = new double[num];
for ( int i = 1 ; i < num ; i++) {
double max = (rest/(num-i+1))*2 ;
double red = rand.nextDouble()*max;
//若金额小于最小值则输出最小值
red = red <= min ? min : red;
rest -= red ;
money[i-1] = red ;
}
money[num-1] = rest;
System.out.println(Arrays.toString(money));
}
public static void main(String[] args) {
fighting();
}
}
萌新写文 请大家多多指教~