Треугольник Паскаля, использующий в основном функции в переполнении стека

Я пытался написать код, который бы отображал треугольник паскалей. Вместо отображения результата как:
введите описание изображения здесь

мой результат отображается как
1
1 1
1 2 1
1 3 3 1

Пожалуйста, помогите мне разобраться, как его изменить, чтобы получить фактический треугольник. Я не могу использовать массивы и указатели, так как они еще не рассмотрены в моем классе. Вот мой код:

#include "stdafx.h"#include <iostream>
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;
PascalsTriangle(n);
return 0;
}

void PascalsTriangle (int n){
int i,j,x;
for(i=0;i<n;i++)
{
x=1;
for(j=0;j<=i;j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}

1

Решение

Вот обновленная версия. Работает на любой 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
2

Другие решения

Попробуй это :

#include <iostream>
using namespace std;
int main()
{
int n,k,i,x;
cout << "Enter a row number for Pascal's Triangle: ";
cin >> n;
for(i=0;i<=n;i++)
{
x=1;
for(k=0;k<=i;k++)
{
cout << x << " ";
x = x * (i - k) / (k + 1);
}
cout << endl;
}
return 0;
}

Редакция:

#include <iostream>
using namespace std;
int main()
{
int n,coef=1,space,i,j;
cout<<"Enter number of rows: ";
cin>>n;
for(i=0;i<n;i++)
{
for(space=1;space<=n-i;space++)
cout<<"  ";
for(j=0;j<=i;j++)
{
if (j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
cout<<"    "<<coef;
}
cout<<endl;
}
}
1

Ожидаете ли вы этого результата?

1111

123

13

1

Вам нужно добавить endl или константную строку, эквивалентную «\ r \ n», в конец выходной строки или использовать запятые в выводе, затем, например:

«1111,123,13,1»

«1,11,121,1331»

0

Если вы хотите, чтобы он выглядел как «треугольник», то есть симметрично выглядящий равнобедренный треугольник, попробуйте этот код для PascalTriangle функция. Единственная проблема заключается в том, что когда вы получаете большие цифры, это нарушит некоторую симметрию, но до 5 строк будет работать нормально.

void PascalsTriangle(int n)
{
int i, j, x;
string len;
for(i = 0; i < n; i++)
{
x = 1;
len = string(n - i - 1, ' ');
cout << len;
for(j = 0; j <= i; j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}

OUTPUT

Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

В отличие от:

Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
0
#include <iostream>

using namespace std;const int MAXC = 13; //-- Max column constant
const int MAXF = 7; //-- Max row constant

int m, n, k, x, y; //-- Counters and accumulators for loops
int arrayTriangulo[MAXF][MAXC]; // Array that stores the values of the Pascal Triangle

int main() {

m = (MAXC/2); // Middle Column
k = (MAXC/2); // Middle row

//-- 1.- Fill in the Array from Left to Right and from Top to Bottom
//-- 2.- Fill in the Array starting from row 0 through 13 (MAXF)

for ( x = 0; x < MAXF; x++ ) {

n = 1;

//-- 3.- Fill in the Array starting from Column 0 through 7 (MAXC)

for ( y = 0; y < MAXC; y++ ) {

//-- Assign 0 to the Array element that is not part of the triangle.

arrayTriangulo[x][y] = 0;

//-- 4.- If it is on the edges of the triangle assigns the value of "n". Which we initialize in 1.

if (( y == m ) || ( y == k )) {
arrayTriangulo[x][y] = n;
}

//-- 5.- For the rest of the internal values of the triangle other than the edges.
//-- The sum of the value is assigned (upper left row -1) + (upper right row + 1)

if ( ( x > 1 ) && ( x < MAXF ) && ( y < MAXC-1 ) ) {
arrayTriangulo[x][y] = arrayTriangulo[x-1][y-1] + arrayTriangulo[x-1][y+1];
}

//-- 6.- Finally Draw the Triangle by omitting the values at zero.

if ( arrayTriangulo[x][y] > 0 )
cout << arrayTriangulo[x][y] << "  ";
else
cout << "   ";

}

cout << endl;
m--;
k++;
}
return 0;
}
0
По вопросам рекламы [email protected]