js初級【偶數求和實戰】

輸入一個數,該數大於1,且計算1到該數之間的所有偶數之和!

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>sum</title>
	<style>
		span{
			font-size: 30px;
			color: red;
		}
	</style>
</head>
<body>
	<p>請輸入任意數字(該值必須大於1),接下來將會計算1到該數字之間的所有偶數之和!</p>
	<input type="text" id="num">    //用於輸入任意數字
	<button type="button" onclick="result()">計算</button>    //提交結果按鈕
	<span id="result"></span>    //該位置用於顯示結果
	<script>	
		function result(){
			//判斷數字的合法性
			var sum = parseInt(document.getElementById('num').value);
            //如果該數字是非數字或者該數字小於1
			if(isNaN(sum) || sum < 1){
                //則返回該警示內容
				alert('您輸入的內容非法,請重試!');
			}

			var j=0;
			for(i=1;i<=sum;i++){
				if(i%2 == 0){    //判斷該值是否能被2整除,說明是偶數
					j += i;
				}				
			}
			document.getElementById('result').innerHTML=j;
		}
	</script>
</body>
</html>

 效果:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章