具有嵌套循环和2维数组的C ++赋值

时间:2018-12-04 15:35:51

标签: c++

需要一些小班教学的帮助,我已经为此工作了几天,但我无法使其正常运行。 这是分配要求:

使用嵌套循环编写程序,该程序要求用户输入要显示的行数的值。然后,它应该显示许多行的星号,第一行有一个星号,第二行有两个,依此类推。对于每一行,星号前面都需要使所有行显示的字符总数等于行数所需的句点数。运行示例如下所示: 输入行数:5
…。*

... **

.. ***

。****

*****

这是我能做的最好的事情

#include <iostream>
int main()
{
    using namespace std;
    int n;
    int col;
    int row;
    cout << "Please enter a number to determine how big the 2-d array will be.\n"; 
    cin >> n;
    char asterisks[n][n];
    for ( row = 0; row < n; row++) 
    { 
        for (col = 0; col < n; ++col) 
        asterisks[row][col] = '.';
    }
    for (col = n; col < 0; col--
    {
        for (row = n; row < 0; --row)
        asterisks[row][col] = '*';
        cout << asterisks[row][col];
        cout << endl;
    }
system ("PAUSE");
return 0;
}

输出为:

请输入数字以确定二维数组的大小。
5
按任意键继续

1 个答案:

答案 0 :(得分:0)

类似这样的事情,没有使用二维数组。

#include <iostream>
int main()
{
    using namespace std;
    cout << "Please enter a number to determine how big the 2-d array will be.\n"; 
    int n;
    cin >> n;
    for (int row = 0; row < n; ++row) 
    { 
        for (int col = 0; col < n; ++col) 
        {
            if (row + col < n - 1)
                cout << '.';
            else
                cout << '*';
        }
        cout << '\n';
    }
    system ("PAUSE");
    return 0;
}

考虑这个问题,您需要打印一个正方形的字符,嵌套在循环中。并且您需要在每个位置决定是打印*还是打印.if (row + col < n - 1)

无需将数据保存在2D阵列中。