字符菱形

GitHub跳转原题关系图返回列表

按行距 g=|r-2| 生成 5 行字符菱形:前导空格数等于 g,字符数等于 5-2g。

OJ: roj

题目 ID: 1028

难度:入门

标签:字符串模拟

创建: 2026-09-29 14:04

更新: 2026-10-04 22:50

题目描述

输入一个字符 cc,输出由它组成的 5 行菱形。第 rr 行(r=0∼4r=0\sim4)为若干前导空格加连续 cc,行尾不留空格。样例 c=*c=\texttt{*}:

text
  *
 ***
*****
 ***
  *

思路

第 rr 行到中间行的距离 g=∣r−2∣g=|r-2| 同时决定前导空格数与字符数:空格数 =g=g,字符数 =5−2g=5-2g。逐行输出即可,注意不要用居中对齐补右侧空格。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 14:06
# update_at: 2026-09-29 14:06

import sys

SIZE = 5  # 菱形对角线长:共 5 行,第 2 行(0 起)是最宽的中间行


def diamond(ch: str) -> str:
    """生成 SIZE 行字符菱形:行到中间行的距离就是前导空格数,字符数按 2 倍距离收窄。"""
    return "\n".join(
        " " * (gap := abs(r - SIZE // 2)) + ch * (SIZE - 2 * gap)  # gap = 该行离中间行多远
        for r in range(SIZE)
    )


def solve() -> None:
    ch = next(iter(sys.stdin.buffer.read().split())).decode()  # 输入只含一个字符
    print(diamond(ch))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-04 22:51
 * update_at: 2026-10-04 22:51
 */

#include <iostream>
#include <cstdlib>
using namespace std;

typedef long long ll;

const int SIZE = 5;          // 菱形共 5 行
const int MID = SIZE / 2;    // 最宽的中间行行号(0 起)

char ch;                     // 输入字符

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> ch;               // 输入只有一个字符

    // 第 r 行离中间行的距离 gap 就是前导空格数,字符数为 SIZE - 2*gap
    for (int r = 0; r < SIZE; r++) {
        int gap = abs(r - MID);
        for (int i = 0; i < gap; i++) cout << ' ';
        for (int i = 0; i < SIZE - 2 * gap; i++) cout << ch;
        cout << '\n';
    }

    return 0;
}