很多同学不理解数学对象是什么?让我们用下面的案例来分析吧
数学对象: Math
关于数学里面数字的处理
目录
一、取整数
1. 向上取整数 (不带小数点)
Math.ceil
console.log(Math.ceil(10.08));// 11
console.log(Math.ceil(100.01));// 101
2.向下取整数
Math.floor
console.log(Math.floor(10.02));// 10
console.log(Math.floor(100.99));// 100
3.四舍五入取整数
Math.round
console.log(Math.round(10.4));// 10
console.log(Math.round(100.5));// 101
二、取绝对值(正数)
1.取绝对值
Math.abs
console.log(Math.abs(-100));// 100
console.log(Math.abs(-55));// 55
三、平方/立方
1.平方/立方
Math.pow
console.log(Math.pow(2,2));// 2 * 2 = 4
console.log(Math.pow(2,3));// 2 * 2 * 2 = 8
四、随机数
1. 获取0~1之间的随机小数
Math.random
console.log(Math.random());// 0 ~ 1 之间的随机小数
2.获取0~10之间的随机数(包含小数点)
Math.random
console.log(Math.random() * 10);
3.获取10~50之间的随机数 (包含小数点)
解题思路:
50-10= 40
先计算0~40之间的随机数 ,再加上10
Math.random
console.log(Math.random() * (最大值 - 最小值) + 最小值 )
console.log(Math.random() * (50 - 10) + 10 )
console.log(Math.random() * 40 + 10)
4.获取20~50之间的随机数 (不包含小数点) ,取整数
var num = Math.random() * 30 + 20;
console.log(Math.floor(num));// 随机整数