'undeclared identifier'错误,即使变量是在代码中先前声明的

Dav*_*ock -6 c cs50

inth当用户输入值时,在第10行声明变量.

但是,当代码编译时,它表示它是未声明的.

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

int main(void)
{
    printf("How tall would you like your pyramid?\n");
    bool inc = true;
    while (inc)
    {
        int h = GetInt();
        if (h <= 23 && h >= 1)
        {
            inc = false;
        }
        else
        {
            printf("your value needs to be between 1 and 26\n");
        }
    }

    for (int i=0; i<=h; i++)
    {
        printf("#\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ken 6

你的变量h在另一座城堡里:

while (inc)
{
    int h = GetInt();
    if (h <= 23 && h >= 1)
    {
        inc = false;
    }
    else
    {
        printf("your value needs to be between 1 and 26\n");
    }
    // h is destroyed after this line and is no longer visible.
}

for (int i=0; i<=h; i++)
{
    printf("#\n");
}
Run Code Online (Sandbox Code Playgroud)

括号表示范围,范围表示可变可见性. hwhile循环范围内声明,在该范围h之外不可见,它}在循环外部不可见.如果你想在循环之外访问它,你应该把它放在循环之外:

int h = -1;
while (inc)
{
    h = GetInt();
    if (h <= 23 && h >= 1)
    {
        inc = false;
    }
    else
    {
        printf("your value needs to be between 1 and 26\n");
    }
}

for (int i=0; i<=h; i++)
{
    printf("#\n");
}
// h is still visible here.
Run Code Online (Sandbox Code Playgroud)

  • `h = GetInt();`应该在循环中. (3认同)