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

如何将含嵌套for循环的倒三角打印代码转换为仅使用嵌套while循环?

转换后的嵌套while循环实现倒三角打印

把原代码中的嵌套for循环替换为while循环的版本如下:

#include <iostream>
using namespace std;

int main() {
    int rows = 5;
    int row = rows;

    while (row >= 1) {
        // 替换打印空格的for循环为while循环
        int space = 1;
        while (space <= rows - row) {
            cout << " ";
            space++;
        }
        // 替换打印星号的for循环为while循环
        int star = 1;
        while (star <= row) {
            cout << "*";
            star++;
        }
        cout << endl; 
        row--; 
    }
    return 0;
}

转换说明

  • 原代码中打印空格的for循环,拆分为三步:初始化space变量、用while判断循环条件、循环体内完成自增操作。
  • 打印星号的for循环同理,拆分出初始化、条件判断、自增的逻辑,对应到while循环结构中。

预期输出

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:05:15