1.计算用户指定的数值内的奇数和,例如用户输入的是10,则计算1 + 3 + 5 + 7 + 9的和;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function sumadd(n){
let sum = 0;
for (let i = 1; i <= n; i ++){
if (i % 2 != 0){
sum += i;
}
}
return sum;
}
let userInput = prompt("请输入一个数字:");
userInput = Number(userInput);
console.log("奇数和为:" + sumadd(userInput));
</script>
</body>
</html>
结果:
2.使用递归计算1 - 100的和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function sum(n) {
if (n <= 0){
return 0;
}else{
return n + sum(n-1);
}
}
console.log(sum(100))
</script>
</body>
</html>
结果: