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)
你的变量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)
括号表示范围,范围表示可变可见性.
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.
Run Code Online (Sandbox Code Playgroud)