在算法題中經常會碰到需要畫金字塔的題, 在這里簡單記錄一下.
一般情況下, 金字塔需要兩層循環, 外層循環代表行數, 內層循環則用來輸出. 我們先來觀察一下這個金字塔.
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
可以看到行數為 5, 每一行的輸出個數等於行數, 且每輸出一個數都會空一格. 那么可以根據這個規律編寫一個算法
#include <iostream>
using namespace std;
int main(void)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
cout << 1 << ' ';
cout << endl;
}
return 0;
}
輸出結果
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
如果想當然的去直接寫結果肯定是錯的. 我們先觀察一下如何輸出第一行的 1. 可以看出當內循環的次數等於達到最大循環次數 + 1 時輸出 1
#include <iostream>
using namespace std;
int main(void)
{
for (int i = 0; i < 5; i++)
{
if (5 == i + 1)
cout << 1 << ' ';
else
cout << ' ';
}
return 0;
}
而且我們繼續觀察會發現, 從第二行開始每一行輸出第一個數的位置都要在前一行輸出第一個數的位置上 - 1, 因此我們就可以得到畫金字塔的算法了
#include <iostream>
using namespace std;
int main(void)
{
int temp = 5;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)
{
if (i + 1 >= temp) /*不止一個數, 因此要 >= */
cout << 1 << ' ';
else
cout << ' ';
}
cout << endl;
temp--;
}
return 0;
}
輸出結果
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
下面再更新一個
#include <iostream>
#include <array>
using namespace std;
int main(void)
{
array<int, 100> A;
int m = 5;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m - i - 1; j++)
cout << ' ';
for (int k = 0; k <= i; k++)
cout << 1 << ' ';
cout << endl;
}
return 0;
}