#include <iostream>
using namespace std;
int main()
{
int** arr;
int N;
cout << "请输入杨辉三角的行数:";
cin >> N;
arr = new int* [N];
for (int i = 0;i < N;i++)
{
arr[i] = new int[N];
}
int i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
arr[i][0] = 1;
arr[i][i] = 1;
}
}
for (i = 2; i < N; ++i)
{
for (j = 1; j < i; ++j)
{
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
for (i = 0; i < N; ++i)
{
for (int k = 0; k < N - i; k++)
{
cout << " ";
}
for (j = 0; j <= i; j++)
{
cout << " " << arr[i][j];
}
cout << endl << endl;
}
cin.get();
for (int i = 0; i < N; i++)
delete[] arr[i], arr[i] = nullptr;
delete[]arr, arr = nullptr;
return 0;
}
只用一维动态数组:
#include<iostream>
using namespace std;
void yhsj(int* const py,int pn)
{
int i, j, k;
py[0] = 1;
cout << py[0] << endl;
for (i = 1; i < pn + 1; i++)
{
py[i] = 1;
for (j=i-1;j>0;j--)
{
py[j] = py[j - 1] + py[j];
}
for (k = 0; k <= i; k++)
{
cout << py[k] << " ";
}
cout << endl;
}
}
int main()
{
int n, * yh;
do
{
cout << "Please input power:\nn=";
cin >> n;
} while (n < 0 || n>20);
yh = new int[n + 1];
yhsj(yh, n);
delete[]yh;
yh = NULL;
}