c ++嵌套循环输出结果

时间:2014-04-09 18:57:47

标签: c++ nested-loops

我想在屏幕上输出这个结果:

  

1
23
456
78910

怎么做? 我试着写这段代码:

for (int line = 1; line <= 4; line++){
    int num = line;
    int i = 1;
    for (int x = 1; x <= line; x++){
        cout << num;
        num = num + i;
    }
    cout << endl;
}

但输出是:

  

1
23
345
4567

请帮助!!!

2 个答案:

答案 0 :(得分:3)

num循环之外创建for并在写完后将其递增。

int num = 1;
for (int line = 1; line <= 4; line++){
    for (int x = 1; x <= line; x++){
        cout << num;
        ++num;
    }
    cout << endl;
}

答案 1 :(得分:1)

int num = 1;
int i = 1;
for (int line = 1; line <= 4; line++){
    for (int x = 1; x <= line; x++){
        cout << num;
        num = num + i;
    }
    cout << endl;
}