大家好。 在本文中,我将向您展示一种打印0-20范围内整数的阶乘表的方法。 请注意,使用此处提供的代码没有任何保证。 我们将使用JavaScript,HTML5和CSS。 要了解有关析因的更多信息,请查看以下链接:
http://en.wikipedia.org/wiki/Factorial 。正整数n(n> = 1)的阶乘由乘积n *(n-1)*(n-2)* ... * 1给出,其中乘以1可以省略,因为它不会在我们的实施中有所作为。 同样,阶乘0被定义为1。首先将显示整个代码,然后我们将逐步进行介绍:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Factorials Table</title>
<meta charset="utf-8">
<!-- CSS styling: -->
<style type="text/css">
table
{
border-spacing: 0;
font-family: Consolas;
font-size: 1.2em;
text-align: right;
}
</style>
<!-- JavaScript code: -->
<script>
var n;
/* Starts table: */
document.writeln( "<table>" );
/* Table's head section: */
document.writeln( "<thead style='background-color: red; color: yellow'>" );
document.writeln( "<tr>" );
document.writeln( "<th>n</th>" );
document.writeln( "<th>n!</th>" );
document.writeln( "</tr>" );
document.writeln( "</thead>" );
/* Table's body section: */
document.writeln( "<tbody>" );
for ( n = 0 ; n <= 20 ; ++n )
{
if ( n % 2 == 0 ) /* Starts new row with black background and white font: */
{
document.writeln( "<tr style='background-color: black; color: white;'>" );
}
else /* Starts new row with blue background and yellow font: */
{
document.writeln( "<tr style='background-color: blue; color: yellow;'>" );
}
/* First column of the current row: */
document.writeln( "<td>" + n + "</td>" );
/* Second column of the current row: */
document.writeln( "<td>" + factorial( n ) + "</td>" );
/* Finishes current row: */
document.writeln( "</tr>" );
}
document.writeln( "</tbody>" );
/* Finishes table: */
document.writeln( "</table>" );
/* Calculates n!: */
function factorial( n )
{
var counter;
var fact = 1;
if ( n < 0 ) /* Invalid argument to function factorial. */
{
return -1;
}
else
{
if ( n >= 1 )
{
for ( counter = 2 ; counter <= n ; ++counter )
{
fact *= counter;
}
}
return fact;
}
}
</script>
</head>
<body></body>
</html>
第1行指定页面的!DOCTYPE ;
在这种情况下,我们指定html ,这意味着该页面是(假设是)HTML5。
<!DOCTYPE html>
第3行开始html标记<html lang="en">
<html lang="en">
第86行关闭了HTML标记</html>
</html>
第4至83行指定页面的head元素。
<head>
. . . . .
</head>
第5行指定页面的标题 。
<title>Factorials Table</title>
第6行指定使用的字符编码。
<meta charset="utf-8">
第8-16行指定页面的样式。 在此页面中,我们仅对
表格元素如下:边框中的间距选择为0 ; font-family是Consolas ,但是如果用户没有这样的字体,我们可以指定更多字体; 选择font-size为1.2em ; 最后,将文本选择为在表格的每个单元格内向右对齐。 我们将很快看到,通过JavaScript代码使用内联样式指定了样式的更多特征。<style type="text/css">
table
{
border-spacing: 0;
font-family: Consolas;
font-size: 1.2em;
text-align: right;
}
</style>
第18-82行包含执行表的计算和输出JavaScript代码。
让我们从第60-81行中定义的阶乘函数开始。
该函数首先声明变量counter和fact ;
事实被初始化为值1,并且计数器将从2变化至n(函数的唯一参数,其阶乘期望被计算)的情况下, 实际上需要改变(它不会如果n <= 0)。
第65-68行检查n是否为负数,如果是,则使该函数返回-1,以表示它接收到无效的,非正整数作为参数。
这不会在我们的页面上发生,但是在工业强度代码中进行错误检查很重要。
如果n> = 0,则使用第69-80行。
如果n为0 ,那么事实应该保持为1 ,并且不执行任何计算。
否则,第73-76行计算n的阶乘。
注意, 计数器从2开始-我们不需要将事实乘以1 。
第79行返回结果。
至于其余的代码,我们有以下内容。 第19行包含以下内容的声明:
n-将要计算其阶乘的变量。 它将在0到20之间变化。第21行输出表开头的标记,在第57行结束。第25-30行输出表的头部,第33-53行输出表的主体,为每个值调用函数阶乘。 n 。From: https://bytes.com/topic/html-css/insights/956601-how-create-factorials-table-javascript-html5-css