任务
一、计算用户指定的数值内的奇数和。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算奇数和</title>
</head>
<body>
<h1>计算奇数和</h1>
<input type="number" id="inputNumber" placeholder="请输入一个整数">
<button οnclick="calculateOddSum()">计算奇数和</button>
<p id="result"></p >
<script>
function calculateOddSum() {
const inputNumber = document.getElementById('inputNumber').value;
let sum = 0;
for (let i = 1; i <= inputNumber; i += 2) {
sum += i;
}
document.getElementById('result').innerHTML = '1到' + inputNumber + '的奇数和为:' + sum;
}
</script>
</body>
</html>
运行结果:
二、使用递归计算1-100的和
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>递归计算1-100的和</title>
<script>
function sum(n) {
if (n === 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
function calculateSum() {
const result = sum(100);
document.getElementById("result").innerHTML = "1-100的和为:" + result;
}
</script>
</head>
<body>
<h1>递归计算1-100的和</h1>
<button οnclick="calculateSum()">计算</button>
<p id="result"></p >
</body>
</html>
运行结果: