6、<简单>打印金字塔星号

一个金字塔星号:

cpp 复制代码
#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "请输入星号行数:";
    cin >> n;
    // 外层循环:控制一共n行
    for (int i = 1; i <= n; i++)
    {
        // 打印前面空格,实现居中
        for (int j = 1; j <= n - i; j++)
        {
            cout << " ";
        }
        // 打印当前行星号:2*i-1个
        for (int k = 1; k <= 2 * i - 1; k++)
        {
            cout << "*";
        }
        // 一行结束换行
        cout << endl;
    }
    return 0;
}
cpp 复制代码
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// 生成单行金字塔字符串(自带前置空格实现内部居中)
string star(int Row, int Line)
{
    string line;
    // 金字塔前置居中空格
    for (int s = 0; s < Row - Line; s++)
        //往字符串末尾添加一个空格
        line += " ";
    // 星号
    for (int c = 0; c < 2 * Line - 1; c++)
        //循环执行生成对应数量的星号。
        line += "*";
    return line;
}

int main()
{
    int rowNum, count;
    cout << "请输入星号行数:";
    cin >> rowNum;
    cout << "请输入并列金字塔个数:";
    cin >> count;

    // 单个区块总宽度 = 金字塔最大宽度 + 间隔留白
    int maxWidth = 2 * rowNum - 1;
    int blockWidth = maxWidth + 6;

    for (int i = 1; i <= rowNum; i++)
    {
        string line = star(rowNum, i);
        // 循环打印所有金字塔
        for (int t = 0; t < count; t++)
        {
            // left:区块内左对齐,统一占位宽度,不会错位
            cout << left << setw(blockWidth) << line;
        }
        cout << endl;
    }
    return 0;
}