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

如何将打印指定图案的C++代码改写为单循环实现

用单个循环实现对称图案打印的C++方案

问题描述

现有一段用于打印指定对称图案的C++代码,采用多层循环实现,需求是将其修改为仅使用一个循环完成图案打印。原代码如下:

#include<iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            cout<<"*";
        }
        for(int j=1;j<=n-i;j++){
            if(j%2!=0){
                cout<<"_";
            }else{
                cout<<".";
            }
        }
        cout<<endl;
    }
    for(int i=1;i<n;i++){
        for(int j=1;j<=n-i;j++){
            cout<<"*";
        }
        for(int j=1;j<=i;j++){
            if(j%2==0){
                cout<<".";
            }else{
                cout<<"_";
            }
        }
        cout<<endl;
    }
}

当n=5时,预期输出为:

*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.

解决方案:单循环实现

核心思路是把所有需要打印的内容(字符+换行)按顺序归入一个一维循环计数,通过计算当前位置对应的行号和列号,判断该输出什么字符。

修改后的代码:

#include<iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    // 总输出数:2n-1行,每行n个字符+1个换行,总次数为(2n-1)*(n+1)
    int total = (2 * n - 1) * (n + 1);
    
    for (int k = 0; k < total; ++k) {
        // 计算当前所在行:每行占n+1个位置(n字符+1换行)
        int row = k / (n + 1);
        // 计算当前行内位置:0~n-1是字符,n是换行
        int col = k % (n + 1);
        
        if (col == n) {
            cout << endl;
            continue;
        }
        
        // 确定当前行的星号数量
        int stars;
        if (row < n) {
            stars = row + 1; // 前n行星号从1递增到n
        } else {
            stars = 2 * n - 1 - row; // 后n-1行星号从n-1递减到1
        }
        
        if (col < stars) {
            cout << "*";
        } else {
            // 补位位置从1开始计数,奇数输出_,偶数输出.
            int pos = col - stars + 1;
            cout << (pos % 2 != 0 ? "_" : ".");
        }
    }
    return 0;
}

思路说明

  1. 总循环次数计算:图案共有2n-1行,每行包含n个字符加1个换行符,因此总循环次数为(2n-1)*(n+1),覆盖所有输出位置。
  2. 行列映射:通过循环变量k计算当前的行号row和列号col,当col等于n时输出换行。
  3. 星号数量判断:
    • 前n行(row < n):星号数量从1递增到n,对应stars = row + 1。
    • 后n-1行(row >= n):星号数量从n-1递减到1,对应stars = 2n -1 - row。
  4. 补位字符逻辑:列号超出星号范围时,计算补位的位置序号,奇数输出_,偶数输出.,和原代码逻辑完全一致。

内容的提问来源于stack exchange,提问作者Ashhar Amir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:05:27