首页 > 代码库 > 数学对象

数学对象

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<script>
//取绝对值
var re = Math.abs(-2.4);
console.log(re);
//取近似整数(如果是整数,向上向下取舍还是它本身)
//四舍五入(四舍五入的结果一定是整数)
var re1 = Math.round(2.4);
console.log(re1);
//对整数进行向下取舍
var re2 = Math.floor(2.4);
console.log(re2);
//对整数进行向上取舍
var re3 = Math.ceil(2.4);
console.log(re3);
//取随机数
//Math.random() (取0-1之间的随机数,取值范围无限接近0) 取x到y之间的随机数公式:Math.random()*((y-x)+x); 取随机整数的公式:Math.floor(Math.random()*((y+1-x)+x));
//例子:我们通常抽奖的概率问题,就拿中与不中两个来比例
var num = Math.random() * (10 - 1 + 1);
if (num < 8) {
console.log("不中");
} else {
console.log("中");
}
//同类例子 以数组形式表现
var arr = ["中", "不中", "不中", "不中", "不中", "不中", "不中", "不中", "不中", "不中", "中", "不中", "中", "不中"];
var result = Math.floor(Math.random() * (arr.length - 1 + 1));
console.log(arr[result]);
</script>
</body>
</html>

数学对象