当用户输入值时,
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");
}
括号表示范围,范围表示变量可见性。
h
在 while
循环的范围内声明,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/