java - % Chance,这段代码高效且正确吗?

标签 java math random netbeans

public class Spell {

    // chance = (0, 100>
    private int chance;

    public void execute() {
        if (chance < 100) {
            /*
            chance:80
            random:40 ... if(true) ... succeed

            chance:80
            random:80 ... if (true) ... failed

            chance:80
            random:81 ... if (true) ... failed

            chance:79
            random:80 ... if (false) ... succeed

            chance:66
            random:<0,65> (66 numbers) ... if (false) ... succeed
            random:<66,99> (34 numbers) ... if (true) ... failed


             */
            if (chance <= (int) (Math.random() * 100)) {
                System.err.println("failed");
                return;
            }

        }
        System.out.println("succeed");

    }

    //Test
    public static void main(String[] args) {
        Spell spell = new Spell();
        spell.chance = 80;
        spell.execute();
    }
}

这是计算机会的正确方法吗?我需要某些事情偶然发生%次。我想知道我在这里是否犯了一些错误或者它是否有效。

假设我们的机会 = 80,我需要它在 80% 的时间里成功,在 20% 的时间里失败。代码中有相关内容,稍后我将在其中添加一个函数。

最佳答案

从数学的角度来看,你的想法是正确的。您固定一个段 [0, 100) 并获得均匀分布的随机数。生成的数字落入段 [0,80) 的概率为 80%。

考虑到问题评论中的建议,代码可能如下所示:

import java.util.Random;

public class Spell {
    private int chance;
    private Random rnd = new Random(System.currentTimeMillis());

    public Spell(int chance) {
        //TODO: Check that chance is inside [0, 100]
        this.chance = chance;
    }

    public void execute() {
        if (rnd.nextInt(100) <= chance)
            System.out.println("succeed");
        else
            System.err.println("failed");
    }
}

最后,您将看到打印有 chance 概率的“succeed”。

关于java - % Chance,这段代码高效且正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173993/

相关文章:

java - 查找Java 8中列表的最大,最小,总和和平均值

java - Spring ResourceBunddleMessageSource 不采用默认的 messages.properties 文件

java - 过滤掉集合中的记录

math - Z80 DAA指令

c++ - 根据一个点围绕中心点旋转了多少找到 2 个点

python - 如何将 python urandom 转换为字符串?

java - 兰顿 Ant 不断沿对角线移动

c++ - 为什么会超时?时间复杂度不是O(n ^ 2logn)吗?

c++ - 在 C++ 中快速添加随机变量

python - TensorFlow:不可重复的结果