使用未声明的标识符' o'

时间:2014-07-28 14:50:49

标签: c cs50

#include <stdio.h>
#include <cs50.h>

int main(void) 
{
    int height;
    {
        printf("Please select a height value between 1-23.");
        height = GetInt();

        while (height < 1 || height > 23)
        {
            printf("Height mustbe between 1-23, please choose new value.\n");
            height = GetInt();
        }
        {
            for (int n = 0; n < height; n++)

            for (int o = 0; o + n + 1 < height; o++)
            {
                printf(" ");
            }            
            for (int p = 0; p <= o; p++)
            {
                printf("#");
            }
        }
    }
}

//我一直收到这个错误:

使用未声明的标识符“o”。     for(int p = 0; p&lt; = o; p ++)                          ^

我在它正上方的行中声明'0',我似乎无法弄清楚为什么它给了我这个错误。请帮助,我是非常新的c,非常感谢任何见解。谢谢!

4 个答案:

答案 0 :(得分:5)

    for (int o = 0; o + n + 1 < height; o++)
    {
        printf(" ");
    } 

    /* o is now out-of-scope */

标识符o的范围在}之后停止。

答案 1 :(得分:4)

for周期标头中声明的变量的范围和生命周期仅限于for周期。它在for周期之外不存在。

答案 2 :(得分:3)

如果变量ofor循环内声明,那么undefined循环之外的变量for 在循环之外声明变量o,例如在函数开头和完成之后。


以下是您完全调试过的代码:

#include <stdio.h>
#include <cs50.h>

int main(void) 
{
    int height, o;
    {
        printf("Please select a height value between 1-23.");
        height = GetInt();

        while (height < 1 || height > 23)
        {
            printf("Height mustbe between 1-23, please choose new value.\n");
            height = GetInt();
        }
        {
            for (int n = 0; n < height; n++)

            for (o = 0; o + n + 1 < height; o++)
            {
                printf(" ");
            }            
            for (int p = 0; p <= o; p++)
            {
                printf("#");
            }
        }
    }
}

答案 3 :(得分:3)

我相信你真正想要的是:

    for (int n = 0; n < height; n++)
    { // not actually necessary - but makes things much clearer.
        for (int o = 0; o + n + 1 < height; o++)
        {
            printf(" ");
            for (int p = 0; p <= o; p++)
            {
                printf("#");
            }
        }            
    }