简体   繁体   English

%Chance,这段代码有效且正确吗?

[英]% Chance, is this code efficient and correct?

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();
    }
}

Is this correct way to calculate chance? 这是计算机会的正确方法吗? I need certain things to happen chance % of times. 我需要一定的事情发生的时候偶然 %。 I wonder whether I did some mistake here or whether it works. 我想知道我是否在这里犯了一些错误或是否有效。

Let's say we have chance = 80, I need it to succeed in 80% of times and fail in 20% of time. 假设我们有机会= 80,我需要它在80%的时间内取得成功,并在20%的时间内失败。 There are souts for that in code, where I will add a function later. 在代码中有一些souts,我稍后会添加一个函数。

From the mathematical point of view your idea is correct. 从数学的角度来看,你的想法是正确的。 You fix a segment [0, 100) and get random number with equal distribution. 您修复了一个段[0,100]并获得具有相同分布的随机数。 The probability that generated number falls into segment [0,80) is 80%. 生成的数字落入段[0,80]的概率为80%。

Taking into account suggestions in comments to your question, the code could look like this: 考虑到对您的问题的评论中的建议,代码可能如下所示:

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

Finally, you will see "succeed" printed with chance probability. 最后,您将看到以chance概率打印的“成功”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM