java模拟发红包

package shousi;

import java.math.BigDecimal;
import java.util.Random;
import java.util.Scanner;

/**
 * 模拟发红包
 */
public class Test4 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入红包金额数");
		double money = sc.nextDouble();
		System.out.println("请输入红包个数");
		int num = sc.nextInt();
		
		BigDecimal[] arr = new Test4().red(new BigDecimal(money), num);
		for (int i = 0; i < arr.length; i++)
			System.out.println("第一个人的红包数是:"+arr[i].doubleValue());
	}
	
	public BigDecimal[] red(BigDecimal money,int num) throws RuntimeException{
		if(money.doubleValue() < num*0.01) {
			throw new RuntimeException("金额不对...");
		}
		
		Random random = new Random();
		//使用分  进行金额运算
		int allMoney = money.multiply(BigDecimal.valueOf(100)).intValue();
		
		int count = 0;//存储所有人的随机点数和
		double[] perCount = new double[num];//存储每一个人的随机点数
		BigDecimal[] perMoney = new BigDecimal[num];//存储每个人的红包金额
		
		//给每个人分配一个随机数
		for (int i = 0; i < perCount.length; i++) {
			int r = random.nextInt((num)*99)+1;
			count += r;
			perCount[i] = r;
		}
		int c = 0;
		//分配红包金额
		for (int i = 0; i < perCount.length; i++) {
			Double x = new Double(perCount[i] / count);
			int m = (int)Math.floor(x*allMoney);
			System.out.println(m);
			if(m == 0)
				m = 1;
			c += m;
			if(i < perCount.length - 1) {
				perMoney[i] = (new BigDecimal(m).divide(new BigDecimal(100)));
			}else {
				perMoney[i] = (new BigDecimal(allMoney - c + m).divide(new BigDecimal(100)));
			}
		}
		return perMoney;
	}

}

发布了114 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44026997/article/details/104773260