Math : 内置的数学对象,只有静态方法和静态方法,Math.对象不能通过new 创建。
1. 派
Math.PI : 圆周率
2. 绝对值
Math.abs()
3. 近似值
1. 四舍五入
Math.round()
注: 负数: > 0.5 进一 <= 0.5 舍去
console.log(Math.PI);
console.log(Math.abs(-3));
console.log(Math.round(4.5)); ///5
console.log(Math.round(4.4)); //4
console.log(Math.round(-4.5)); //-4
console.log(Math.round(-4.500000001)); //-5
console.log(Math.round(-4.4)); //-4
2. 向下取整
Math.floor()
3. 向上取整
Math.ceil()
console.log(Math.ceil(4.5)); //5
console.log(Math.ceil(4.4)); //5
console.log(Math.ceil(-4.5)); //-4
console.log(Math.ceil(-4.4)); //-4
4. 最值
1. 最大值
Math.max()
Math.max.apply(null,数组)
var arr = [5,2,3,1,5,4];
console.log(Math.max.apply(null,arr));
2. 最小值
Math.min()
Math.min.apply(null,数组)
var arr = [5,2,3,1,5,4];
console.log(Math.min(5,2,3,1,5,4));
console.log(Math.min.apply(null,arr));
5. 随机数*****
Math.random() 0 <= num < 1
Math.floor(Math.random() * (max - min + 1) + min)
Math.ceil(Math.random() * (max - min) + min);
console.log(Math.floor(Math.random() * 10)); //0~9
console.log(Math.floor(Math.random() * 10 + 1)); //1 ~ 10
console.log(Math.floor(Math.random() * 3 + 3)); //0~2 + 3 //3~5 5 - 3 + 1 (max - min + 1 ) + min
console.log(Math.floor(Math.random() * 6 + 5));
console.log(randomInt(1,3));
*/
function randomInt(min,max){
if(min > max){
var t = min;
min = max;
max = t;
}
return Math.floor(Math.random() * (max - min + 1) + min);
}
while(1){
var pc = randomInt(1,3);
var player = parseInt(prompt(' 1 :石头 2 :剪刀 3 :布 0 : 退出\n请选择:'));
if(player == 0){
break;
}
switch(pc){
case 1 :
switch(player){
case 1 : alert('平局');break;
case 2 : alert('您输了');break;
case 3 : alert('您赢了');break;
default : alert('错误');
} break;
case 2 :
switch(player){
case 1 : alert('您赢了');break;
case 2 :alert('平局');break;
case 3 :alert('您输了');break;
default : alert('错误');
} break;
case 3 :
switch(player){
case 1 : alert('您输了');break;
case 2 :alert('您赢了');break;
case 3 :alert('平局');break;
default : alert('错误');
} break;
}
}
08#Math
最新推荐文章于 2022-11-15 16:22:42 发布