Java 随机百分比机会 [英] Java Random Percentage Chance

查看:65
本文介绍了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
}

这篇关于Java 随机百分比机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆