js文件
function $(id)
{
return document.getElementById(id);
}
function sum(n1,n2)
{
for(var i=n1,sum1=0;i<=n2;i++)
{
sum1=sum1+i;
}
return sum1;
}
function show()
{
var n11=parseFloat($("start_num").value);
var n22=parseFloat($("end_num").value);
if(n11>0 && n22>0)
{
if(n11>=n22)
{
alert("起始数必须小于终止数,请重输!");
$("start_num").value="";
$("end_num").value="";
}
else{
$("sum").value=sum(n11,n22);
}
}
else{
alert("请输入数据!");
$("start_num").focus();
}
}
html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>计算自然数之和</title>
<style type="text/css">
#div{text-align: center;margin:20px auto 20px auto ;line-height: 1.5em;border: 18px groove #66FF66;width: 560px;height: 260;font-weight: bold;}
form{margin: 20px auto 20px auto;padding: 5px;}
</style>
<script type="text/javascript" src="sum.js">
</script>
</head>
<body>
<div id="div">
<h3>计算机任意区间内连续自然数的累加和</h3>
<form method="post"action="">
<h3>定义区间</h3>
<label>起始数</label><input type="text" id="start_num" name="start_num"/>
<label>终止数</label><input type="text" id="end_num" name="end_num"/>
<br>
<label>累加和</label><input type="text" id="sum" name="sum" readonly="readonly"/>
<br>
<input type="button" value="计算" onclick="show();">
<input type="reset" name="" id="" value="清空">
</form>
</div>
</body>
</html>
网友评论