用HTML写一个定义函数 getRandomInt(),返回一个在指定值之间的随机整数。这个值不小于min(如果 min不是整数,则不小于min的向上取整数),且小于(不等于)max。函数 getRandomInt()调用 次数。请写出 示例如下: console.log( getRandomInt(5.3,10));// 输出:6 console.log( getRandomInt(5,10));// 输出:9
时间: 2024-02-23 20:02:23 浏览: 20
好的,这是一个HTML中定义函数的例子:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>getRandomInt</title>
<script>
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
console.log(getRandomInt(5.3, 10));
console.log(getRandomInt(5, 10));
</script>
</head>
<body>
<h1>getRandomInt</h1>
<p>请在控制台查看输出结果</p>
</body>
</html>
```
这个例子中,我们定义了一个名为 `getRandomInt` 的函数,它接受两个参数 `min` 和 `max`,并返回一个在指定范围内的随机整数。
在函数体内,我们首先对 `min` 进行了向上取整,确保它是整数。然后使用 `Math.floor` 和 `Math.random` 方法生成一个介于 `min` 和 `max` 之间(不包括 `max`)的随机整数。最后返回这个随机整数。
在页面加载时,我们调用了两次 `getRandomInt` 函数,并将结果输出到控制台中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)