大括号 - 递归

curly brackets - recursion

本文关键字:递归      更新时间:2023-10-16

我之前读过一些关于使用大括号的问题,据我了解,如果你只有一行,不使用大括号是可以的,但如果你要使用多行代码,你需要使用括号。

我有一个作业,老师确实要求我们在每种情况下都使用括号,以养成好习惯。他还允许我们研究和使用示例代码。

现在,我的问题是,我找到了一些不使用括号的示例代码。当我尝试将括号添加到代码中时,它会使我的输出不正确。有人可以向我解释如何在多行代码中正确使用大括号,并就如何实现我正在寻找的结果提出建议。

这是输出正确的代码:

void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{ 
if(i == n)
{
    for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
    for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
} 
    else
    {
        for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
        printStars(i+1, n); // recursive invocation
        for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
    }
} // printStars
int main() {
    int n;
    int i=0;
        cout << "Enter the number of lines  in the grid: ";
        cin>> n;
        cout << endl;
        printStars(i,n);
    return 0;
}

当我尝试"清理它"时,如下所示:

void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
{
    if(i == n)
    {
        for(int j = 1; j <= n; j++)
        {
            cout << '*';
            cout << endl;
        }
        for(int j = 1; j <= n; j++)
        {
            cout << '*';
            cout << endl;
        }
    }
    else
    {
        for(int j = 1; j <= i; j++)
        {
            cout << '*';
            cout << endl;
        }
        printStars(i+1, n); // recursive invocation
        for(int j = 1; j <= i; j++)
        {
            cout << '*';
            cout << endl;
        }
    }
} // printStars
int main() {
    int n;
    int i=0;
        cout << "Enter the number of lines  in the grid: ";
        cin>> n;
        cout << endl;
        printStars(i,n);
    return 0;
}

问题是你在打印循环中放了太多:

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

应该是:

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

不带大括号的循环只能包含一个语句。这意味着仅在循环结束时调用使用 cout 的行尾打印。

这是使用大括号的完整代码:

void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{ 
if(i == n)
{
    for(int j = 1; j <= n; j++){
        cout << '*';
    }
    cout << endl;
    for(int j = 1; j <= n; j++){
        cout << '*';
    }
    cout << endl;
} 
    else
    {
        for(int j = 1; j <= i; j++){
            cout << '*';
        }
        cout << endl;
        printStars(i+1, n); // recursive invocation
        for(int j = 1; j <= i; j++){
            cout << '*';
        }
        cout << endl;
    }
} // printStars
int main() {
    int n;
    int i=0;
        cout << "Enter the number of lines  in the grid: ";
        cin>> n;
        cout << endl;
        printStars(i,n);
    return 0;
}