You need to enable JavaScript to run this app. 不使用嵌套for循环如何按行列打印实心矩形?可否用递归实现?
优惠活动
大模型
产品
解决方案
定价
更多

不使用嵌套for循环如何按行列打印实心矩形?可否用递归实现?

去掉嵌套for循环的优化方案

你可以直接用std::string的构造函数省略内层循环,string(c, '*')可以直接生成一个长度为c、全为*的字符串,只需一层循环打印r次即可,相比原嵌套循环减少了多次单字符输出的开销,性能更好:

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

int main ()
{
    int r,c;
    cout<<"Enter the number of rows and then columns:\n";
    cin>>r>>c;
    cout<<"Pattern:\n";
    string line(c, '*');
    for(int i=0; i<r; i++) {
        cout << line << '\n';
    }
    return 0;
}

递归实现方案

完全可以通过递归实现该需求,不需要任何显式的for循环,分为两种实现思路:

思路1:配合string构造的递归

只需一层递归控制行数即可,逻辑更简洁:

  • 递归边界条件:剩余需要打印的行数为0时直接终止递归
  • 核心逻辑:每次递归打印一行全*字符串,再传入行数减1调用自身
#include <iostream>
#include <string>
using namespace std;

void printRect(int remainingRows, const string& line) {
    // 递归边界
    if (remainingRows <= 0) return;
    cout << line << '\n';
    printRect(remainingRows - 1, line);
}

int main ()
{
    int r,c;
    cout<<"Enter the number of rows and then columns:\n";
    cin>>r>>c;
    cout<<"Pattern:\n";
    printRect(r, string(c, '*'));
    return 0;
}

思路2:纯递归无依赖实现

如果不想依赖string构造,可以用两层递归分别控制行数和每行的字符数:

  • 行数递归边界:剩余需要打印的行数为0时直接返回
  • 单行字符递归边界:剩余需要打印的字符数为0时打印换行后返回
#include <iostream>
using namespace std;

// 递归打印单行
void printLine(int remainingCols) {
    if (remainingCols <= 0) {
        cout << '\n';
        return;
    }
    cout << '*';
    printLine(remainingCols - 1);
}

// 递归打印整个矩形
void printRect(int remainingRows, int cols) {
    if (remainingRows <= 0) return;
    printLine(cols);
    printRect(remainingRows - 1, cols);
}

int main ()
{
    int r,c;
    cout<<"Enter the number of rows and then columns:\n";
    cin>>r>>c;
    cout<<"Pattern:\n";
    printRect(r, c);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:27:04