为了账号安全,请及时绑定邮箱和手机立即绑定

【九月打卡】第18天 JavaScript进阶篇

标签:
JavaScript

课程名称JavaScript进阶篇

课程章节:第7章 JavaScript内置对象

课程讲师:  慕课官方号

课程内容

向上取整ceil()

ceil() 方法可对一个数进行向上取整。

语法:

Math.ceil(x)


参数说明:

注意:它返回的是大于或等于x,并且与x最接近的整数。

我们将把 ceil() 方法运用到不同的数字上,代码如下:

<script type="text/javascript">
  document.write(Math.ceil(0.8) + "<br />")
  document.write(Math.ceil(6.3) + "<br />")
  document.write(Math.ceil(5) + "<br />")
  document.write(Math.ceil(3.5) + "<br />")
  document.write(Math.ceil(-5.1) + "<br />")
  document.write(Math.ceil(-5.9))
</script>

 

运行结果:

1
7
5
4
-5
-5

编程练习

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
 document.write(Math.ceil(3.3) + "<br />")
  document.write(Math.ceil(-0.1) + "<br />")
  document.write(Math.ceil(-9.9) + "<br />")
  document.write(Math.ceil(8.9) + "<br />")
  document.write(Math.ceil(Math.PI) + "<br />")
  document.write(Math.ceil(Math.cos(0)-0.1))
</script>
</head>
<body>
</body>
</html>

向下取整floor()

floor() 方法可对一个数进行向下取整。

语法:

Math.floor(x)


参数说明:

注意:返回的是小于或等于x,并且与 x 最接近的整数。

我们将在不同的数字上使用 floor() 方法,代码如下:

<script type="text/javascript">
  document.write(Math.floor(0.8)+ "<br>")
  document.write(Math.floor(6.3)+ "<br>")
  document.write(Math.floor(5)+ "<br>")
  document.write(Math.floor(3.5)+ "<br>")
  document.write(Math.floor(-5.1)+ "<br>")
  document.write(Math.floor(-5.9))
</script>


运行结果:


0
6
5
3
-6
-6

向下取整

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
function math(x){
    document.write(Math.floor(x)+"<br/>");
}
math(3.3);
math(-0.1);
math(-9.9);
math(8.9);
</script>
</head>
<body>
</body>
</html>

四舍五入round()

round() 方法可把一个数字四舍五入为最接近的整数。

语法:

Math.round(x)


参数说明:

注意:

1. 返回与 x 最接近的整数。

2. 对于 0.5,该方法将进行上舍入。(5.5 将舍入为 6)

3. 如果 x 与两侧整数同等接近,则结果接近 +∞方向的数字值 。(如 -5.5 将舍入为 -5; -5.52 将舍入为 -6),如下图:

把不同的数舍入为最接近的整数,代码如下:

<script type="text/javascript">
  document.write(Math.round(1.6)+ "<br>");
  document.write(Math.round(2.5)+ "<br>");
  document.write(Math.round(0.49)+ "<br>");
  document.write(Math.round(-6.4)+ "<br>");
  document.write(Math.round(-6.6));</script>

 

运行结果:

2
3
0
-6
-7

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
function math(x){
    document.write(Math.round(x)+"<br>");
}
math(3.3);
math(-0.1);
math(-9.9);
math(8.9);
</script>
</head>
<body>
</body>
</html>              

课程收获

谢谢老师,讲的非常细致,很容易懂。这一节学习了向上取整,向下取整和四舍五入,通过学习我了解了这些方法在什么情况下使用,给以后的学习打下了基础。以及对数据有了新的认识,期待后边的学习!


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消