2016-12-24 108 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);