#include
using namespace std;
int main()
{ int n;cin>>n;
int s[n][n];
for(int i=0;i<=n-1;i++)
s[i][0] = 1;
for(int i=1;i<=n-1;i++)
{
for(int j=1;j<=i;j++)
{
s[i][j] = s[i-1][j] + s[i-1][j-1];
}
}
for(int i=0;i<=n-1;i++)
{
for(int j=0;j<=i;j++)
cout<< s[i][j]<<"\t";
cout<<endl;
}
return 0;
}
for循环有问题,数组里面的值没有初始化完。需要if判断i j关系
可以对比一下
#include <iostream>
#include <iomanip>
using namespace std;
#define N 256
int main(void) {
int n = 0;
int a[N][N] = { 0 };
cout << "请输入要打印的杨辉三角形行数:";
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
a[i][j] = 1;
}
else {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
}
for (int i = 0; i < n; i++) {
int width = (n - i) * 2;
cout << setw(width) << a[i][0];
for (int j = 1; j <= i; j++) {
cout << setw(4) << a[i][j];
}
cout << endl;
}
system("pause");
return 0;
}