2016-12-24 96 views
-3
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之间我不断收到错误,称该变量需要初始化。故障使用输入while循环

我敢肯定,这是一个很小的事情,但我不知道如何评估或更正它C.

+3

“廉政towerh; 做{printf的 (“给我一个整数1到23之间,我会做一个塔”); 012htowerh = GetInt(); (towerh <1 || towerh> 23);' –

+0

你应该添加标签cs50 –

+1

问题是你有两个变量叫'towerh',一个在循环体内声明,一个在外面。循环条件测试循环外部定义的变量,但由'GetInt()'读取的值被分配给循环内定义的变量。这在大括号中超出了范围。您应该简单地将'int'放入循环中以分配给循环外定义的变量。这就是达尔顿水槽所说明的 - 但没有完全解释。 –

回答

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

努力,我得到一个错误的声明阴影局部变量 –

+0

你尝试的完整代码或只是初始化之后?阴影变量意味着你在你的代码重新创建在相同名称的变量,比如你用'循环 – Uriel

+0

只是初始化我得到它现在固定感谢您的帮助内INT towerh'做 –

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);