<%
int sum=1
if(num<0){//判断传入数是否为负数
throw new IllegalArgumentException("必须为正整数!")//抛出不合理参数异常
}
for(int i=1i<=5i++){//循环num
sum *= i//每循环一次进行乘法运算
}
out.print("5的阶乘计算结果:"+sum)//返回阶乘的值
%>
参考代码:
<%@ page language="java" contentType="text/html charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8">
<title>阶乘计算</title>
</head>
<body>
<%
for (int i = 1 i <= 10 i++) {
int fac = 1
for (int j = 1 j <= i j++) {
fac *= j
}
out.print(i + "的阶乘为:" + fac + "<br>")
}
%>
</body>
</html>
运行结果:
首先你定义的变量M应为1,如果为零,结果全为零,以下供你参考一下%@ page contentType="text/htmlcharset=GB2312" %>
<HTML><BODY >
<h3>这是计算5的阶乘并输出在页面中...</h3>
<% int n, sum=1
for(n=1n<=5n++)
{ sum=sum*n
}
%>
<br>1到5的阶乘是:
<%=sum %>
</BODY><HTML>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)