Javascript怎么实现Math.sqrt函数

JavaScript019

Javascript怎么实现Math.sqrt函数,第1张

//自定义 Math 类<br>var MyMath=(function(){<br>

var diff=0.00000000001//精度<br>

var GetSqrt= function(n){ <br>

var s = n / 2//假设的平方根初值 <br>

while (NotFit(s,n)) { <br>

s = ((n / s) + s) / 2<br>

} <br>

return s<br>

},NotFit=function( num, n){ <br>

var r= num*num<br>

var d = Abs(n - Abs(r))<br>

if(d>diff){ <br>

return true<br>

}<br>

return false<br>

},Abs=function(a){<br>

if(a>=0 )return a<br>

else return -a<br>

}<br><br>

return {<br>

sqrt:GetSqrt,<br>

abs:Abs<br>

}<br>})()<br><br>//sqrt<br>alert(MyMath.sqrt(0))//0<br>alert(MyMath.sqrt(1))//1<br>alert(MyMath.sqrt(9))//3<br><br>//abs<br>alert(MyMath.abs(-4))//4上面的代码自己测试可以运行

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<%

String path = request.getContextPath()

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script type="text/javascript">

function getById(id){

return document.getElementById(id)

}

function getInfo(){

var num=getById("num").value

if(isNaN(num) || num<1){

alert("请输入正整数!")

}else{

alert(num+"的平方值为:"+num*num)

alert(num+"的平方根为:"+Math.sqrt(num))

}

}

</script>

</head>

<body>

<input type="text" size="20" id="num"><input type="button" value="计算" onclick="getInfo()">

</body>

</html>

楼主,望采纳啊,^_^,给点评价哦 ,可以结贴了。绝对没问题

JS中可以通过sqrt获得数字的平方根

JS中我们可以通过sqrt()函数获得数字的平方根.语法如下:

Math.sqrt(x)

下面来看一些sqrt()实例:

<script language='JavaScript' type='text/JavaScript'>

<!--

document.write(Math.sqrt(4))// output is 2

document.write("<br>")

document.write(Math.sqrt(64))// output is 8

document.write("<br>")

document.write(Math.sqrt(9))// output is 3

document.write("<br>")

document.write(Math.sqrt(27))// output is 5.196152422706632

document.write("<br>")

document.write(Math.sqrt(0.36))// output is 0.6

document.write("<br>------------<br>")

document.write(Math.sqrt(-64))// output is Nan

document.write("<br>")

document.write(Math.sqrt(-9))// output is NaN

//-->

</script>