请用Java写一个发红包的代码,参数有红包总金额,红包个数,可以控制2个包位数为7
时间: 2024-03-14 20:47:19 浏览: 97
好的,以下是一个简单的Java程序,用于发放红包,其中参数为红包总金额和红包个数,同时可以控制2个包位数为7:
```
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedPacket {
private static final int MAX_SCALE = 2;
private static final int RANDOM_COUNT = 20;
public static List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int totalCount) {
if (totalAmount == null || totalCount <= 0) {
return null;
}
List<BigDecimal> result = new ArrayList<>();
BigDecimal currentAmount = BigDecimal.ZERO;
for (int i = 1; i <= totalCount; i++) {
if (i == totalCount) {
result.add(totalAmount.subtract(currentAmount));
} else {
BigDecimal maxAmount = totalAmount.subtract(currentAmount).subtract(BigDecimal.valueOf(totalCount - i));
BigDecimal randomAmount = getRandomAmount(maxAmount, totalCount - i);
result.add(randomAmount);
currentAmount = currentAmount.add(randomAmount);
}
}
return result;
}
private static BigDecimal getRandomAmount(BigDecimal maxAmount, int count) {
BigDecimal randomAmount = BigDecimal.ZERO;
Random random = new Random();
int scale = maxAmount.scale() <= MAX_SCALE ? maxAmount.scale() : MAX_SCALE;
for (int i = 1; i <= RANDOM_COUNT; i++) {
randomAmount = maxAmount.multiply(BigDecimal.valueOf(random.nextDouble())).setScale(scale, BigDecimal.ROUND_HALF_UP);
if (randomAmount.compareTo(BigDecimal.ZERO) > 0 && randomAmount.compareTo(maxAmount.divide(BigDecimal.valueOf(count), scale, BigDecimal.ROUND_HALF_UP)) <= 0) {
break;
}
}
return randomAmount;
}
public static void main(String[] args) {
BigDecimal totalAmount = BigDecimal.valueOf(1000);
int totalCount = 10;
List<BigDecimal> result = divideRedPacket(totalAmount, totalCount);
if (result == null) {
System.out.println("参数错误");
return;
}
for (BigDecimal amount : result) {
if (amount != null) {
System.out.println(amount.setScale(2, BigDecimal.ROUND_HALF_UP));
}
}
}
}
```
请注意,上面的代码仅作为示例,实际应用中可能需要更严格的参数校验和算法优化。同时,如果您想控制2个包位数为7,可以通过修改`getRandomAmount`方法中的`scale`参数来实现。
阅读全文