JS中Math函数的常用方法

JavaScript06

JS中Math函数的常用方法,第1张

JS中Math函数的常用方法

Math是数学函数,但又属于对象数据类型typeof Math=>‘object’

console.dir(Math)查看Math的所有函数方法。

1,Math.abs()获取绝对值

Math.abs(-12) = 12

2,Math.ceil() and Math.floor()向上取整和向下取整

console.log(Math.ceil(12.03))//13

console.log(Math.ceil(12.92))//13

console.log(Math.floor(12.3))//12

console.log(Math.floor(12.9))//12

3,Math.round()四舍五入

注意:正数时,包含5是向上取整,负数时包含5是向下取整。

1、Math.round(-16.3) = -16

2、Math.round(-16.5) = -16

3、Math.round(-16.51) = -17

4,Math.random()取[0,1)的随机小数

案例1:获取[0,10]的随机整数

console.log(parseInt(Math.random()*10))//未包含10

console.log(parseInt(Math.random()*10+1))//包含10

案例2:获取[n,m]之间的随机整数

Math.round(Math.random()*(m-n)+n)

5,Math.max() and Max.min()获取一组数据中的最大值和最小值

console.log(Math.max(10,1,9,100,200,45,78))

console.log(Math.min(10,1,9,100,200,45,78))

6,Math.PI获取圆周率π 的值

console.log(Math.PI)

7,Math.pow() and Math.sqrt()

Math.pow()获取一个值的多少次幂

Math.sqrt()对数值开方

Math.pow(10,2) = 100

Math.sqrt(100) = 10

方法一:用C语言中自带的绝对值函数表示:

如果a是整数:

#include<stdio.h>

#include<math.h>

int a=100,b;

b=abs(a);

printf("%d",b);

如果a是浮点数:

#include<stdio.h>

#include<math.h>

float a=99.9;

float b

b=fabs(a);

printf("%f",b);

方法二:自己编写一个函数表示:

#include <stdio.h>

int abs(int t)

{

if (t>0)

return t;

else

return -t;

}

int main()

{

int t = 0;

scanf("%d",&t);

printf("%d",abs(t));

return 0;

}

以上两种方法均可以实现求得绝对值。但使用abs函数时,需要将头文件#include<math.h>包含到源文件中。

扩展资料:

在C语言中,绝对值可以用库函数fabs或abs来表示。

fabs表示对double型数据取绝对值。

abs表示对int型数据取绝对值。

函数原型是:double fabs(double x)。