#include <stdio.h>
#include <cs50.h>
int main (void)
{
printf("Welcome to blabla\n");
// This next part gets user input and checks if the integer given by user is between 1 and 8
int n;
do
{
printf("Give me a integer between 1 and 8.\n");
int n = GetInt();
}
while (n >= 1 && n <= 8);
printf("You picked the number %d.\n", n);
return(0);
}
答案 0 :(得分:4)
更改
int n = GetInt();
与
n = GetInt();
您正在引入第二个变量n
,其中的块范围将在第一个}
之后被丢弃。自动对象的生命周期在声明它的块的末尾结束。
答案 1 :(得分:2)
您在循环内重新声明n
,因此不使用外部声明。这可能不是你想要的。
替换
int n = GetInt();
使用:
n = GetInt();
答案 2 :(得分:2)
这一行:
int n = GetInt();
尝试声明 new 本地变量n
。它与您之前声明的局部变量完全分开:
int n;
当您致电GetInt()
时,您只想将值分配给现有变量,如下所示:
n = GetInt();
答案 3 :(得分:0)
为什么你在do {}内再次声明n为int n?只需将其更改为:
n = GetInt();
内在n的范围直到do的'}'。之后它从未使用过。循环外的n是使用的n