用java怎样将一个正整数L随机拆分成N个正整数

2025-02-03 06:05:41
推荐回答(1个)
回答1:

试试这个代码

import java.util.Random;

public class Test {
    public static void main(String[] args)throws Exception{   
        random(5, 100);
    }

    public static void random(int n, int L){
        Random rand = new Random();
        int temp = L;
        for(int i = 0, j; i < n-1; i++){
            j = rand.nextInt(temp-1) + 1;
            temp -= j;
            System.out.println(j);
        }
        System.out.println(temp);
    }
}