javascript实例教程(17-2)


 
  舍入函数和随机数字

Math.random()

产生从0到1的随机数

Math.round(x)

取最接近整数x的数值

Math.floor(x)

取最接近整数x并且比x小的数值

Math.ceil(x)

取最接近整数x并且比x大的数值

Math.min(a, b, c)

返回参数列表中最小的数值

Math.max(a, b, c)

返回参数列表中最大的数值



这里注意:函数Math.random()只能在Unix版本的Navigator 2.0执行。

这些函数中最常用的就是产生在给定两个数值之间的随机数。以下的函数就是一个很好的例子:

function randomvalue(low, high) {

alert(Math.floor(Math.random() * (1 + high - low) + low));

}

另外,你可以在复杂的代码中使用with语句来避免Math标识符的重复使用,例如以下代码:

function randomvalue(low, high) {

with (Math) {

alert(floor(random() * (1 + high - low) + low));

}

}

这里要记住,Math.random()函数只能在Unix版本的Navigator 2.0执行,而不能在windows版本的浏览器中执行,所以这个函数我们一般不使用。

以下给出的是一个更复杂的函数。这个函数返回三角形第三边的长度,给出的条件是三角形的两边及两边的夹角。具体代码如下:

function findside(sidea, sideb, angle) {

with (Math) {

var tmp = pow(sidea, 2) + pow(sideb, 2) - 2 * sidea * sideb * cos(angle);

alert("side length is " + sqrt(tmp));

}

}

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3