1,计算用户指定的数值内的奇数和
效果运行图:
代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>计算用户指定的数值内的奇数和</title>
</head>
<body><script>let input = prompt('请输入一个正整数')let number = parseInt(input)let sum = 0if(number<0){console.log('输入有误,请重新输入')}else{for(let i = 1; i <= number; i+=2){sum += i}}console.log(sum)</script>
</body>
</html>
2,使用递归计算 1 ~ 100 的和
效果运行图:
代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用递归计算 1 ~ 100 的和</title>
</head>
<body>
<script>function sum1(num){if(num === 1) return 1return num + sum1(num-1)}let number = prompt('请输入一个1~100整数')number = parseInt(number)console.log(sum1(number))
</script>
</body>
</html>