Java 随机概率

Java Random Percentage Chance

谁能帮我展示一下如何用百分比计算概率/几率?

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.");
        }
    }
}

我的程序正确吗?

Ty

不,你的程序不正确。

当您调用 nextInt(10) 时,您会得到一个 0 到 9(含)范围内的数字。然后将其细分为所需的概率范围,而无需重复使用数字:

  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
}

或者你可以走另一条路:

//   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
}