所以首先帕斯卡三角是這樣的:如何修改我的程序以打印出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