1.简单写法
public class test01 {
public static void main(String args[]) {
int money = 1000;
//可能会出现随机数太小,造成没有分到钱
double a = Math.random();
double b = Math.random();
double c = Math.random();
double sum = a + b + c;
int a1 = (int) (a / sum * money);
int b1 = (int) (b / sum * money);
int c1 = money - a1 - b1;
System.out.println( a1 / 100.0);
System.out.println( b1 / 100.0);
System.out.println( c1 / 100.0);
}
}
2.改善写法
public class test01 {
public static void main(String args[]) {
int money = 1000;
money -= 3;
double a = Math.random();
double b = Math.random();
double c = Math.random();
double sum = a + b + c;
int a1 = (int) (a / sum * money);
int b1 = (int) (b / sum * money);
int c1 = money - a1 - b1;
a1 += 1;
b1 += 1;
c1 += 1;
System.out.println(a1 / 100.0);
System.out.println(b1 / 100.0);
System.out.println(c1 / 100.0);
}
}