使用while循环输入问题

时间:2016-12-24 23:59:16

标签: c variables global local cs50

int towerh;
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    int towerh = GetInt();
}while (towerh < 1 || towerh > 23);

只要towerh不在1到23之间,我就试图创建这个代码块循环。我不断收到错误,说明需要初始化变量。

我确信这是一件小事,但我不知道如何在C中评估或纠正它。

2 个答案:

答案 0 :(得分:1)

只需将int towerh;更改为int towerh = 0;即可。这称为初始化变量,通常C编译器在你错过它时讨厌。

此外,您在循环中反复创建towerh,我建议scanf覆盖未提及的GetInt,因此您可以结束:

int towerh = 0;
do {
    printf("Give me an integer between 1 and 23 and I will make a tower: ");
    scanf("%d", &towerh);
} while (towerh < 1 || towerh > 23);

答案 1 :(得分:1)

代码有2 towerh;。第一个从未设置

int towerh;  // 1st, never initialized nor assigned.
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    int towerh = GetInt(); // 2nd, not the same object as the outer towerh

//      v----v        v----v  Uses the 1st towerh
}while (towerh < 1 || towerh > 23);

而只使用1。

int towerh;  // One and only towerh
do{
    printf ("give me an integer between 1 and 23 and I will make a tower");
    // int towerh = GetInt();
    towerh = GetInt();
}while (towerh < 1 || towerh > 23);