第一题:
<!DOCTYPE html>
<html>
<head>
<title>计算奇数和</title>
</head>
<body>
<label for="input">请输入一个正整数:</label>
<input type="number" id="input">
<button onclick="calculate()">计算</button>
<p id="result"></p>
<script>
function calculate() {
let input = parseInt(document.getElementById("input").value);
let result = 0;
for (let i = 1; i <= input; i += 2) {
result += i;
}
document.getElementById("result").innerHTML = `1 + 3 + 5 + ... + ${input} = ${result}`;
}
</script>
</body>
</html>
运行结果:
第二题:
<!DOCTYPE html>
<html>
<head>
<title>计算1 ~ 100的和</title>
</head>
<body>
<button onclick="displayResult()">计算</button>
<p id="result"></p>
<script>
function calculateSum(num) {
if (num === undefined) {
num = 1; // 默认从 1 开始
}
if (num > 100) {
return 0; // 递归终止条件
}
return num + calculateSum(num + 1); // 递归调用
}
function displayResult() {
document.getElementById("result").innerHTML = `1 + 2 + 3 + ... + 100 = ${calculateSum()}`;
}
</script>
</body>
</html>
运行结果: