4. 用JavaScript编写一个Web程序,计算1!+2!+3!+4!+5!,并显示出结果。要求先声明计算阶乘的方法,再调用该方法,最后在页面上输出结果。进阶要求,通过表单提交一个正整数,然后计算它的阶乘和。例如:输入3,就计算1!+2!+3!。若换成用JSP编写,又将如何完成?
时间: 2023-05-20 17:05:14 浏览: 110
以下是用 JavaScript 编写一个 Web 程序,计算 1! 2! 3! 4! 5! 并显示出结果的代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>阶乘计算器</title>
</head>
<body>
<script>
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
var result = factorial(1) * factorial(2) * factorial(3) * factorial(4) * factorial(5);
document.write(result);
</script>
</body>
</html>
```
如果要通过表单提交一个正整数,然后计算它的阶乘和,可以用以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>阶乘计算器</title>
</head>
<body>
<form>
<label for="number">请输入一个正整数:</label>
<input type="number" id="number" name="number">
<button type="button" onclick="calculate()">计算</button>
</form>
<div id="result"></div>
<script>
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
function calculate() {
var number = parseInt(document.getElementById("number").value);
var result = 1;
for (var i = 1; i <= number; i++) {
result *= factorial(i);
}
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
```
如果用 JSP 编写,可以使用类似以下的代码:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>阶乘计算器</title>
</head>
<body>
<form>
<label for="number">请输入一个正整数:</label>
<input type="number" id="number" name="number">
<button type="button" onclick="calculate()">计算</button>
</form>
<div id="result"></div>
<script>
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
function calculate() {
var number = parseInt(document.getElementById("number").value);
var result = 1;
for (var i = 1; i <= number; i++) {
result *= factorial(i);
}
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
```
阅读全文