Java 随机百分比机会
问题描述:
谁能帮我展示如何用百分比计算概率/机会?
Someone can u help me to show how to make a probability / chance with percentage ?
import java.util.Random;
public class Main {
public static void main(String[] args) {
int a = new Random().nextInt(10);
if (a >= 6) {
// 60% chance
System.out.println(a);
System.out.println("You got a passive power");
} else if (a >= 3) {
// 30% chance
System.out.println(a);
System.out.println("You got an active power");
} else if (a >= 1) {
// 10% chance
System.out.println(a);
System.out.println("You got an ultimate power");
} else {
// <10% chance (maybe)
System.out.println(a);
System.out.println("You blessed with all powers.");
}
}
}
我的程序正确吗?
你
答
不,您的程序不正确.
当您调用 nextInt(10)
时,您会得到一个范围为 0 到 9(包括 0 到 9)的数字.然后您将其分割成您想要的概率范围,而无需重复使用数字:
When you call nextInt(10)
, you get a number in range 0 to 9, inclusive. You then segment that into the probability ranges you want, without reusing a number:
0 1 2 3 4 5 6 7 8 9
└──────────────┘ └─────┘ ╵
6 / 10 = 60% 30% 10%
这意味着代码应该是:
int a = new Random().nextInt(10);
if (a < 6) {
// 60% chance
} else if (a < 9) {
// 30% chance
} else {
// 10% chance
}
或者你可以走另一条路:
Or you could go the other way:
// 0 1 2 3 4 5 6 7 8 9
// ╵ └─────┘ └──────────────┘
// 10% 30% 60%
int a = new Random().nextInt(10);
if (a >= 4) {
// 60% chance
} else if (a >= 1) {
// 30% chance
} else {
// 10% chance
}