c - 即使在代码的前面声明了变量,也会出现“未声明的标识符”错误

标签 c cs50

当用户输入值时,

int 变量 h 在第 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");
    }
}

最佳答案

你的变量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");
}

括号表示范围,范围表示变量可见性。 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.

关于c - 即使在代码的前面声明了变量,也会出现“未声明的标识符”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697485/

相关文章:

我可以在返回类型指针的函数中返回变量的地址吗?

sql - ORACLE Pro*C/C++ 代码未对结果进行舍入

c - 在 C 中为动态数字输入读取字符串时出现问题

c - 为什么即使值为真,我的 while 循环也会继续执行?

C:输出带有凯撒密码加密中的符号,为什么? pset2 CS50

c - 计算CS50练习中的硬币变化困难

c - EDK2(UEFI 开发环境)在执行测试构建后失败

C 中的冲突类型错误与某些文件 io

c - 如何正确处理一个巨大的字符串?

c - 如何打印某个字符和空格后的字符