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

C++中蝴蝶图案嵌套for循环的工作原理及列号疑惑解答

蝴蝶图案C++代码的循环机制解析

以下是实现蝴蝶图案的C++代码:

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;

    // Upper part of the butterfly
    for (int i = 1; i <= n; i++) {
        // Print stars
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }

        // Print spaces
        int space = 2 * (n - i);
        for (int j = 1; j <= space; j++) {
            cout << " ";
        }

        // Print stars for the second set
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }

        cout << endl;
    }

    // Lower part of the butterfly
    for (int i = n; i >= 1; i--) {
        // Print stars
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }

        // Print spaces
        int space = 2 * (n - i);
        for (int j = 1; j <= space; j++) {
            cout << " ";
        }

        // Print stars
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }

        cout << endl;
    }

    return 0;
}

当输入n=4时,程序输出如下:

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

对应的列号分布:

1 2 3 4 5 6 7 8 - 列号 

 1 *             *
 2 * *         * *
 3 * * *     * * *
 4 * * * * * * * *
 5 * * * * * * * *
 6 * * *     * * *
 7 * *         * *
 8 *             *
 |
 行号

疑问

观察列号时,误以为上半部分第二组星号的j<=i循环条件(比如第1行i=1)无法让第二个星号出现在第8列,但输出却正确,想了解该for循环的实际工作机制。


循环机制解析

你混淆了循环变量j的作用和星号的最终列号:

  • 第二个星号循环的j<=i,不是用来控制星号的列位置,而是控制这一组要打印的星号数量。
  • 以第1行(i=1)为例:
    1. 第一个循环打印i=1个星号,占据第1列;
    2. 中间的空格循环计算出space=2*(4-1)=6,打印6个空格,占据第2到第7列;
    3. 第二个星号循环打印i=1个星号,这个星号会紧跟在6个空格之后,也就是第8列。
  • 循环变量j只是用来计数:从1到i,每循环一次输出一个星号,总共输出i个星号,和星号最终的列号没有直接关联,列号是由前面的星号+空格的总长度决定的。

简单说,第二个星号循环的任务就是输出i个星号,它的位置是“自动衔接”在前面的内容之后,而不是由j的值来指定列号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:10:54