JavaScript数学函数知识综合运用

数学函数

1.写一个函数limit2,保留数字小数点后两位,四舍五入, 如: (**)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function limit2 (num) {
var num1 = num*100
if(num1 >= 0){
num1 = Math.round(num1)
}else{
num1 = -Math.round(Math.abs(num1));
}
num = num1/100;
console.log(num);
return num;
}
var num1 = 3.456
limit2( num1 ); //3.46
limit2( 2.42 ); //2.42

2.写一个函数,获取从min到max之间的随机数,包括min不包括max (*

1
2
3
4
5
function ranAmong (min,max) {
return min+Math.random()*(max-min);
}
console.log(ranAmong(4,15));
console.log(ranAmong(14,21));

3.写一个函数,获取从min都max之间的随机整数,包括min包括max (*

1
2
3
4
5
function ranAmong (min,max) {
return Math.round(min+Math.random()*(max-min));
}
console.log(ranAmong(4,15));
console.log(ranAmong(14,21))

4.写一个函数,获取一个随机数组,数组中元素为长度为len,最小值为min,最大值为max(包括)的随机数 (*

1
2
3
4
5
6
7
8
9
function ranAmong (min,max,len) {
var arr = [];
for (var i = 0; i < len; i++) {
arr.push(Math.round(min+Math.random()*(max-min)));
};
return arr;
}
console.log(ranAmong(2,17,5));
console.log(ranAmong(12,14,3));
文章目录
  1. 1. 数学函数
    1. 1.1. 1.写一个函数limit2,保留数字小数点后两位,四舍五入, 如: (**)
    2. 1.2. 2.写一个函数,获取从min到max之间的随机数,包括min不包括max (*)
    3. 1.3. 3.写一个函数,获取从min都max之间的随机整数,包括min包括max (*)
    4. 1.4. 4.写一个函数,获取一个随机数组,数组中元素为长度为len,最小值为min,最大值为max(包括)的随机数 (*)
,