[英]Method that returns true or false at x percentage
i'm looking for a method that answers randomly true or false by a given percentage Integer. 我正在寻找一种方法,通过给定的百分比整数随机地回答真或假。 for example: 例如:
percent(100); //Will always 100% return true
percent(50); //Will return 50% true, or 50% false
percent(0); //Will always 100% return false, etc..
Here is what I came up with, but for some reason it's not working as it should be: 这是我想出来的,但由于某种原因,它不能正常工作:
public static boolean percent(int percentage)
{
Random rand = new Random();
return ((rand.nextInt((100-percentage)+1))+percentage)>=percentage;
}
I need a very accurate and real method, please help it's too complicated it's giving me a headache 我需要一个非常准确和真实的方法,请帮助它太复杂它让我头疼
I believe you are just overthinking it: 我相信你只是在思考它:
return (rand.nextInt(100) < percentage);
Should work fine. 应该工作正常。
I would break it into smaller pieces to understand: 我会把它分成小块来理解:
public boolean rollDie(int percentGiven)
{
Random rand = new Random();
int roll = rand.nextInt(100);
if(roll < percentGiven)
return true;
else
return false;
}
Frequently, naming conventions and breaking code across more lines (instead of many method calls stacked in a single line) can make it easier to solve problems. 通常,命名约定和跨越更多行的代码(而不是堆叠在一行中的许多方法调用)可以更容易地解决问题。 Here I am using explicit names that make it easy to read. 在这里,我使用明确的名称,使其易于阅读。 This is good for beginners like me that do not do well interpreting very compact code. 对于像我这样的初学者来说,这对于解释非常紧凑的代码并不是很好。
public boolean percent(int p){
Random r=new Random();
return r.nextInt(100)<p;
}
It should be easy enough if you pick up a random number between 1-100. 如果您在1-100之间选择一个随机数,这应该很容易。 For example 55 for the case percent(50) this will be false if you assume that the number between 1-50 are true and the rest are false. 例如对于百分比(50)的55,如果您假设1-50之间的数字为真且其余为假,则这将为假。 Given the fact that you accept that rand() is totally random this shoud solve your problem. 鉴于你接受rand()完全随机的事实,这应该解决你的问题。
So 所以
if (random_num >= percent)
changed if (random_num >= percent)
发生了变化
return true;
else
return false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.