num1、num2 是随机数的界限,但如果 num1 大于 num2,我希望结果为 0。
int num1 = 5
int num2 = 1
int num3 = 10
Random rand = new Random();
double num = 0;
for (int i = 0; i < num3; i++) {
int randNum = rand.nextInt((num2 - num1) + 1) + num1;
num = num + randNum;
// Adds the random number generated to num until it reaches the
// max amount of numbers generated.
}
num = num / num3;
if (num3 < 1 || num2 < num1){
return 0;
} else {
return num;
}
我认为最后一个 if 语句会起作用,但它一直给我一个错误,提示随机数不能为负数。
如果解决方案可以简单一点,因为我才刚刚开始使用 Java
任何帮助将不胜感激,谢谢
最佳答案
因为(根据Javadocs)
public int nextInt(int n)
Parameters: n - the bound on the random number to be returned. Must be positive. Returns: the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence Throws: IllegalArgumentException - if n is not positive
返回一个伪随机、在 0(含)和指定值(不含)之间均匀分布的 int 值
所以你需要首先检查 (num2 - num1) > 0
关于java - 如果随机数为负数,如何返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21471119/