【分享】一些經典的C/C++語言基礎算法及代碼(二)

閱讀到的一些經典C/C++語言算法及代碼。在此分享。

4、打印三角形和金字塔

用" * "打印半金字塔

#include <iostream>
using namespace std;

int main()
{
    int rows;
    int i, j;
    cout << " Enter the number of rows: " << endl;
    cin >> rows;
    for (i = 1; i <= rows; ++i)  // i行
    {
        for (j = 1; j <= i; ++j)  // j列
        {
            cout << "* ";
        }
        cout << "\n" << endl;
    }
}

用數字打印三角形

#include <iostream>
using namespace std;

int main()
{
    int rows, i, j;
    cout << " Enter the number of rows: " << endl;
    cin >> rows;
    for (i = 1; i <= rows; ++i)
    {
        for (j = 1; j <= i; ++j)
        {
            cout << j << " "; // 將上一個代碼中輸出的"*"換爲"j "即可
        }
        cout << "\n" << endl;
    }
}

用"*"打印金字塔

//將金字塔從中線分爲左右各一半
#include <iostream>
using namespace std;

int main()
{
    int rows, i, space;
    int j = 0;
    cout << " Enter the number of rows: " << endl;
    cin >> rows;
    for(i = 1; i <= rows; ++i)
    {
        for (space = 1; space <= rows - i; ++space)
        {
            cout << "  ";
        }
        while (j != 2 * i - 1)
        {
            cout << "* ";
            ++j;
        }
        j = 0;
        cout << "\n";
    }
    return 0;
}

用"*"打印倒金字塔

//從上到下變位從下到上
#include <iostream>
using namespace std;

int main()
{
    int rows, i, j, space;
    cout << " Enter the number of rows: " << endl;
    cin >> rows;
    for(i = rows; i >= 1; --i)
    {
        for (space = 0; space <= rows - i; ++space)
            cout << "  ";
        for (j = i; j <=2 * i - 1; ++j)
            cout << "* ";
        for (j = 0; j < i-1; ++j)
            cout << "* ";
        cout << "\n";

    }
    return 0;
}

5月4日更新

結合上面的方法,編寫出一個打印棱形的程序

#include<iostream>
using namespace std;

int main()
{
    int i, j, rows, space;
    cout << "Enter rows: " << endl;
    cin >> rows;
    for(i = 1; i <= rows; ++i)
    {
        for(space = 1; space <= rows - i; ++space)
        {
            cout << "  ";
        }
        for(j = 1; j <= 2 * i - 1; ++j)
        {
            cout << "* ";
        }
        cout << endl;
    }
    for(i = rows - 1; i >= 1; --i)
    {
        for(space = 1; space <= rows - i; ++space)
        {
            cout << "  ";
        }
        for(j = 1; j <= 2 * i - 1; ++j)
        {
            cout << "* ";
        }
        cout << endl;
    }
}

今天看到@天花板 的一篇內容可以對上述程序進行優化。代碼就不貼了,上連接:21天C語言代碼訓練營(第二天)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章