所以首先帕斯卡三角是这样的:如何修改我的程序以打印出Pascal的三角形?
您看到的第一行是零第i行。
当你是一名计算机科学家时,这并不罕见 。
C(N,K)= N:
在帕斯卡三角形每个术语可以与下式的组合来预测!/[k! *(n - k)!],其中“n”是行,“k”是从零到n的任何整数。
所以由此可以得出帕斯卡三角可以用(N,K)组合预测:
这就是你在上图中看到的。
帕斯卡三角基本上是二项式概率:
(H + T)^ N#你翻转双面硬币“N”次,它的土地上的“正面”或“反面”和你收集的频率(H + T)^ 3 = 1(H^3)+ 3(H^2)(T)+ 3(H)每个在一组系数中,对于n = 3,我们得到扩展: (T^2)+1(T^3),其中这些系数: 1,3,3,1在帕斯卡三角形的第3行。
我定义了一个阶乘,和组合,并能够与一些循环Perl代码获得帕斯卡三角的任何行的 系数号(!):
use strict;
use warnings;
# Note the first row is row 0.
print("\nWhich row of Pascal's triangle to display: ");
my $row = <STDIN>; # The row that you want to display # This is also n.
my $terms = $row + 1; # The number of terms is one more than the row number.
Pascal_Row($row); # Print the Pascal numbers for that row.
# Function displays the numbers for a row of Pascal's triangle.
#######################################################
sub Pascal_Row
{
my $row = shift; # Row is passed in.
for(my $k = 0; $k < $row + 1; $k++) # k alternates, but not the row which is n.
{
print(combination($row, $k), "\t") # Print each row.
}
print("\n"); # Print a newline after each time this function is called.
}
# This computes the factorial of a number.
###########################################
sub factorial
{
my $number = shift; # argument.
my $factorial_number = 1; # initalize the factorial.
for(my $i = 1; $i <= $number; $i++)
{
$factorial_number *= $i; # compute the factorial, by multiplying all terms up to and including number.
}
return $factorial_number; # Return the factorial number.
}
# Computes a matehmatical combination usually denoted as C(n, k)
# where n is the row number, and k is each item in a row of Pascal's traingle
sub combination
{
my($n, $k) = @_; # from input.
# This is the mathematical formula for a combination.
my $combination_number = factorial($n)/(factorial($k) * factorial($n - $k));
return $combination_number # And returning it.
}
如果我运行代码,并要求杨辉三角的第8行,我得到这样的:
Which row of Pascal's triangle to display: 8
1 8 28 56 70 56 28 8 1
这对杨辉三角的第8行完全正确的。如果我从第0行循环到Pascal三角形的第8行,我会得到所有正确的Pascal三角形行,但它看起来不像一个三角形(它看起来更像一个盒子),所以我怎么修改我的代码来调整缩进。
如果我想要显示8行Pascal三角形,我该如何决定缩进第一行多少?我怎样才能做出一个“三角形”?
你知道你要多少行有,这意味着你知道你是从底部多少行:下面
整个剧本中给出。每行的第一个数字在下一行的第一个数字和第二个数字之间的一半,所以它必须被用于行上数字的间距的一半。用那个武装......乘以! – hobbs
在这种情况下,我不应该用制表符分隔行上的每个系数吗? – xyz123
是的,你会遇到一个问题,一直沿着tabstops。我会建议看看'printf'的固定宽度输出:) – hobbs