JAVA實(shí)現(xiàn)紅包分發(fā)的示例代碼
如果發(fā)總金額為 m mm 的 n nn 個(gè)紅包,先用一個(gè)長度為 n nn 的臨時(shí)數(shù)組 a aa 存放 n nn 個(gè)隨機(jī)雙精度小數(shù) ,然后用 s u m sumsum 表示數(shù)組 a aa 的和,每個(gè)紅包的金額
代碼import java.util.Arrays;import java.util.Random;import java.math.*;import java.util.Scanner;public class Main { public static long now_time; public static long seed; public static int[] get_red_packets(int money, int num) { Random random = new Random(seed); seed = random.nextLong(); int[] res = new int[num]; double[] temp=new double[num]; double sum = 0; int sum2 = 0; for (int i = 0; i < num; i++) { temp[i] = random.nextDouble(); sum += temp[i]; } for (int i = 0; i < num; i++) { res[i] = 1+ (int)(temp[i] / sum * (money-num)); sum2 += res[i]-1; } res[random.nextInt(num)]+=money-sum2-num; return res; } public static void show(int[] red_packet){ System.out.println('紅包 : ' + Arrays.toString(red_packet)); } public static void main(String[] args) { int num, money; Scanner scanner = new Scanner(System.in); now_time = System.currentTimeMillis(); Random init_random = new Random(now_time); seed = init_random.nextLong(); System.out.println('請輸入要分發(fā)的紅包數(shù)量:'); num = scanner.nextInt(); System.out.println('請輸入要分發(fā)的紅包總金額(分):'); money = scanner.nextInt(); int a[] = get_red_packets(money,num); show(a); }}
到此這篇關(guān)于JAVA實(shí)現(xiàn)紅包分發(fā)的示例代碼的文章就介紹到這了,更多相關(guān)JAVA 紅包分發(fā)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)3. Xml簡介_動力節(jié)點(diǎn)Java學(xué)院整理4. jsp文件下載功能實(shí)現(xiàn)代碼5. 詳解瀏覽器的緩存機(jī)制6. JSP之表單提交get和post的區(qū)別詳解及實(shí)例7. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器8. xml中的空格之完全解說9. 如何在jsp界面中插入圖片10. phpstudy apache開啟ssi使用詳解
