int
变量h
。
然而,当代码编译时,它表示未声明。
#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");
}
}
答案 0 :(得分: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");
}
括号表示范围,范围表示可变可见性。
在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.