JS 函数 求圆的面积总结

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS 函数</title>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
<body>
<script type="text/javascript">

//1.
function circle(r)
{
this.r=r
this.Area=Area
this.Circum=Circum
}
function Circum()
{
return(3.14*2*this.r) 
}
function Area()
{
return(3.14*this.r*this.r)
}
r=parseInt(prompt("请输入半径:"," ")); // parseInt() 函数可解析一个字符串,并返回一个整数
var newcircle=new circle(r);
var Circumcapital=newcircle.Circum();
var Areacapital=newcircle.Area();
document.write("周长:"+Circumcapital+";");
document.write("面积:"+Areacapital+" ");


//2.
var area_of_circle = new Function("r","return r*r*Math.PI"); //创建一个函数对象
var rCircle1 = 2;//给定圆的半径

var area = area_of_circle(rCircle1);
alert("半径为2的圆面积为:" + area);
var rCircle2 = 3;//给定圆的半径
var area = area_of_circle(rCircle2);

alert("半径为3的圆面积为:" + area);



//3.
var r=prompt("输入圆的半径","请输入半径:");//prompt() 方法用于显示可提示用户进行输入的对话框
   if(r!=null)
   {
       var square=r*r*Math.PI;
       document.write("圆的面积为:"+square);
   }
   else
   {
       alert("输入数据有误");
   }





</script>


</body>

</html>


1.、2.和3.三种不同的方法求圆的面积,第一种方法中增加了周长的计算方法,第二种方法中我给area_of_circle(面积)定义了一个公共函数,不管半径是多少都可以调用面积这个函数,节省了求面积的函数的复写。第三种方法注意prompt()函数,第三个有一个if判断,判断是否输入无效

猜你喜欢

转载自blog.csdn.net/qq_35774189/article/details/71308577