double min = 0.0001;
double max = 10; // 总和
int cnt = 5; // 数量
int scl = 4; // 小数最大位数
int pow = (int) Math.pow(10, scl); // 用于提取指定小数位
double sum = 0; // 用于验证总和
double one ;
for (int i = 0; i < cnt; i ++) {
if ( i < cnt - 1 ) {
// min~max 指定小数位的随机数
one = Math.floor((Math.random() * (max - min) + min) * pow) / pow;
} else {
one = max;
}
max -= one;
sum += one;
// 输出
System.out.printf("%.4f\r\n", one);
}
// 验证
System.out.println(sum);
/*
演示输出:
6.7665
1.7457
0.0602
1.0894
0.3382
10.0
*/
If you want the gap between random numbers to be smaller, you can modify the calculation formula of one, such as replacing max - min with max / (cnt - i). Of course, you have to pay attention to the value of min to avoid one being a negative number in the end.
If this is the test question of the subject, I think the test point should be to take a random number between the specified m~n. For the sake of my troublesome answer, brothers passing by can give me a thumbs up.
If you want the gap between random numbers to be smaller, you can modify the calculation formula of one, such as replacing max - min with max / (cnt - i). Of course, you have to pay attention to the value of min to avoid one being a negative number in the end.
If this is the test question of the subject, I think the test point should be to take a random number between the specified m~n. For the sake of my troublesome answer, brothers passing by can give me a thumbs up.
It can only guarantee that the sum is equal, but the result is not very uniform and is often top-heavy