这是更新的版本。适用于任何n
. 我添加了一个函数来返回数字中的位数,因为内部循环的每次迭代都需要计算。
#include <iostream>
#include <string>
using namespace std;
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
cin >> n;
cout << endl;
PascalsTriangle(n);
return 0;
}
int numdigits(int x)
{
int count = 0;
while(x != 0) {
x = x / 10;
++count;
}
return count;
}
void PascalsTriangle (int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
len = string((n-i-1)*(n/2), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x) - 1;
if(n % 2 == 0)
cout << y << string(n - 1 - maxlen, ' ');
else {
cout << y << string(n - 2 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUTS:
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
UPDATE for a more tighter triangle:
void PascalsTriangle(int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
if(n % 2 != 0)
len = string((n-i-1)*(n/2), ' ');
else
len = string((n-i-1)*((n/2)-1), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x);
if(n % 2 == 0)
cout << y << string(n - 2 - maxlen, ' ');
else {
cout << y << string(n - 1 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1