【发布时间】:2019-05-02 00:41:13
【问题描述】:
我正在努力完成实用程序方法以生成 2 个整数范围内的数字,该数字也是另一个整数的乘数。
例如:
public static void main(String[] args) {
getIntegerInRangeMultipleOf(100, 1000, 444);
}
应该产生 444 或 888。没有别的了。
我想出了这个解决方案:
public static int getIntegerInRangeMultipleOf(int minInclusive, int maxInclusive, int multiplier) {
return Math.toIntExact(Math.round((Math.random() * (maxInclusive - minInclusive) + minInclusive) / multiplier) * multiplier);
}
但对于上面的示例,除了 444 和 888 之外,有时它还会产生 0(零)。
请建议如何修复该功能。
【问题讨论】:
-
您在 900 的范围内构建了一个阶跃函数,将结果四舍五入到最接近的 444。
444和888的可能性是否相同,或者是否存在某种加权,因为范围是更大? -
根本没有暗示权重。 444 和 888 的可能性应该相等。
标签: java algorithm random integer