案例–基本函数案例
编写一个函数,计算两个数字的和差积商
方法1:
function calculate(num1, num2, sign) {
switch(sign){
case "+":
alert(num1 + "+" + num2 + "=" + (num1 + num2));
break;
case "-":
alert(num1 + "-" + num2 + "=" + (num1 - num2));
break;
case "*":
alert(num1 + "*" + num2 + "=" + (num1 * num2));
break;
case "/":
alert(num1 + "/" + num2 + "=" + (num1 / num2));
break;
}
}
calculate(1,2,"/");
方法2:
function calculate() {
num1 = Number(prompt('请输入第一个数'));
sign = prompt('请输入运算符');
num2 = Number(prompt('请输入第二个数'));
switch(sign){
case "+":
alert(num1 + "+" + num2 + "=" + (num1 + num2));
break;
case "-":
alert(num1 + "-" + num2 + "=" + (num1 - num2));
break;
case "*":
alert(num1 + "*" + num2 + "=" + (num1 * num2));
break;
case "/":
alert(num1 + "/" + num2 + "=" + (num1 / num2));
break;
default:
alert("数据错误")
}
}
calculate();
编写函数,求圆的面积
var area = function(r){
s=Math.PI*r*r;
alert(s);
}
area(4);