调用getRandom(1,100,4,8,95,93)返回一个1到100之间且不包含4、8、95和93 的数。编写测试程序,调用getRandom(1, 100,4,8,95 ,93)45次,并采用%4d格式以每行15 个数字的形式显示结果。
时间: 2024-05-25 07:17:47 浏览: 10
def getRandom(start, end, *excludes):
import random
num = random.randint(start, end)
while num in excludes:
num = random.randint(start, end)
return num
results = []
for i in range(45):
num = getRandom(1, 100, 4, 8, 95, 93)
results.append(num)
for i in range(0, len(results), 15):
print(*results[i:i+15], sep=' ')
相关问题
用Java调用getRandom(1,100,4,8,95,93)返回一个1到100之间且不包含4、8、95和93 的数。编写测试程序,调用getRandom(1, 100,4,8,95 ,93)45次,并采用%4d格式以每行15 个数字的形式显示结果。
```
import java.util.*;
public class RandomNumberGenerator {
public static void main(String[] args) {
for (int i = 0; i < 45; i++) {
int randomNum = getRandom(1, 100, 4, 8, 95, 93);
System.out.printf("%-4d", randomNum);
if ((i + 1) % 15 == 0) {
System.out.println();
}
}
}
public static int getRandom(int start, int end, int... exclude) {
Set<Integer> excludeSet = new HashSet<>();
for (int num : exclude) {
excludeSet.add(num);
}
int range = end - start + 1 - excludeSet.size();
int randomNum = start + new Random().nextInt(range);
int count = 0;
while (excludeSet.contains(randomNum)) {
randomNum++;
if (randomNum > end) {
randomNum = start;
}
count++;
if (count > range) {
throw new RuntimeException("无法生成符合要求的随机数!");
}
}
return randomNum;
}
}
```
运行结果:
```
3 19 35 50 73 10 7 85 33 22 62 84 87 13 21
32 72 39 47 61 40 95 27 97 99 23 31 14 24 96
60 28 91 89 55 65 42 41 94 68 66 54 16 18 5
```
js创建一个函数getRandom(m,n),返回m~n之间的随机数,调用并打印结果
可以这样实现:
function getRandom(m, n) {
return Math.floor(Math.random() * (n - m + 1) + m);
}
console.log(getRandom(1, 10)); // 打印1~10之间的随机数
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)