与嵌套循环作斗争

问题描述 投票:0回答:1

提前感谢您抽出时间。我是一名非常新手的程序员,进入我的旅程大约两周了。我今天正在学习嵌套循环并感到困惑。

我正在大学学习 C++,并且也在关注 Mosh 的在线教程。

我对“星号输出”有点困惑。 (我用谷歌搜索并阅读了其他帖子)

我输入5时当前的输出是:

*
*
*
*
*

我正在努力获得:

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

使用以下代码:

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
    cout << "Rows: ";
    int rows;
    cin >> rows;

    for (int i = 1; i <= rows; i++) {
        for (int j = 0; j < i; j++)
            cout << "*";
    cout << endl;
}  


我尝试编写自己的,然后完全复制Mosh的,但我仍然没有得到正确的结果。谢谢您的宝贵时间!!

c++ loops nested
1个回答
0
投票

您的代码的唯一问题是它缺少右括号。除此之外,一切都应该返回预期的结果。

int main() {
    cout << "Rows: ";
    int rows;
    cin >> rows;

    for (int i = 1; i <= rows; i++) {
        for (int j = 0; j < i; j++)
            cout << "*";
        cout << endl;
    } // missing bracket here and weird indenting
}
© www.soinside.com 2019 - 2024. All rights reserved.