解决这个问题,代码如下:
<script type="text/javascript">var a = 1var b = 2var sum = parseInt(a) + parseInt(b)</script>
1
2
3
4
5
parseInt()是js的解析字符串的函数,返回解析后的数字。
var num=100mySum=new sum2()
document.write("方法1:1+...+100="+sum(num))
document.write("<br/>方法2:1+...+100="+mySum.calc(num))
document.write("<br/>方法3:1+...+100="+sum3(num))
document.write("<br/>方法4:1+...+100="+sum4(num))
//方法1
function sum(num) {
res=0
for(i=1i<=numi++)
res+=i
return res
}
//方法2
function sum2() {
this.res = 0
this.calc = function(num) {
if (num == 1)
return this.res = 1
return this.res = num + this.calc(num-1)
}
}
//方法3
function sum3(num) {
res=0
while(num>0) {
res+=num
num--
}
return res
}
//方法4
function sum4(num) {
res=0
if(num%2==0)
res=(num+1)*(num/2)
else
res=num+(num-1+1)*((num-1)/2)
return res
}