You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++嵌套循环实现特定星号图案:行数大于7时图案变形问题

修复奇数行对称星号图案的变形问题

需求说明

需要实现如下对称星号图案(以5行为例),仅支持奇数行数作为可变参数:

*****
 ***
  *
 ***
*****

现有代码在行数为5或7时输出正常,但行数大于7时图案出现变形,以下是问题排查与修复方案。

问题定位

错误出现在上半部分(第一行到中间行)的星号数量计算逻辑:
原代码中计算星数的表达式为:

2 * (trows - rowno) - (trows + 1) / 2

该表达式仅在trows=5或7时凑巧得到正确值,当行数更大时(如9),计算结果会偏离实际需要的星数(比如trows=9、rowno=1时,原公式算出11个星,正确应为9个),直接导致图案变形。

修复方案

根据图案规律:上半部分每一行的星数比上一行少2,第一行星数等于总行数trows,中间行仅1个星。因此正确的星数计算公式为:

trows - 2*(rowno - 1)

或通过中间行mid=(trows+1)/2推导等价公式:2*(mid - rowno) +1,两者效果一致。

修复后的完整代码

#include <iostream>
using namespace std;
int main()
{
    int trows, rowno = 1;
    cout << "Enter total no. of rows: ";
    cin >> trows;
    int mid = (trows + 1) / 2; // 提前计算中间行,减少重复计算

    // 输出上半部分(含中间行)
    while (rowno <= mid) {
        // 打印前置空格
        int space = 1;
        while (space <= rowno - 1) {
            cout << ' ';
            space++;
        }
        // 打印星号
        int star = 1;
        int star_count = trows - 2 * (rowno - 1);
        while (star <= star_count) {
            cout << '*';
            star++;
        }
        cout << endl;
        rowno++;
    }

    // 输出下半部分
    rowno = mid + 1;
    while (rowno <= trows) {
        // 打印前置空格
        int space = 1;
        while (space <= trows - rowno) {
            cout << ' ';
            space++;
        }
        // 打印星号(原逻辑正确,无需修改)
        int star = 1;
        int star_count = 2 * rowno - trows;
        while (star <= star_count) {
            cout << '*';
            star++;
        }
        cout << endl;
        rowno++;
    }
    return 0;
}

验证效果

输入9行时,输出图案如下,符合预期:

*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********

内容的提问来源于stack exchange,提问作者SHREYASH KUMAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:50:22