2014-09-06 98 views
0

在我們開始之前,是的,這是作業,不,我不想讓別人來做我的功課。我有一個問題,有人輸入一個最多7位數字的二進制數字,只需將該數字從二進制數字改爲十進制數字即可。雖然我當然不會使用最高效/最好的方法,但我確信我可以使它工作。讓我們看看代碼:C++無關for循環需要程序成功運行

#include <iostream> 
#include <math.h> 

using namespace std; 

int main() { 
    char numbers[8]; 
    int number = 0, error = 0; 

    cout << "Please input a binary number (up to 7 digits)\nBinary: "; 

    cin.get(numbers, 8); 
    cin.ignore(80, '\n'); 

    for (int z = 7; z >= 0; z--){} 
    cout << "\n"; 

    for (int i = 0, x = 7; x >= 0; x--, i++){ 
     if (numbers[x] <= 0){ // if that is an empty space in the array. 
      i--; 
     } 
     else if (numbers[x] == '1'){ 
      number += pow(2, i); 
     } 
     else if (numbers[x] != '0'){ // if something other than a 0, 1, or empty space is in the array. 
      error = 1; 
      x = -1; 
     } 
    } 
    if (error){ // if a char other than 0 or 1 was input this should print. 
     cout << "That isn't a binary number.\n"; 
    } 
    else{ 
     cout << numbers << " is " << number << " in decimal.\n"; 
    } 
    return 0; 
} 

如果我運行此代碼,它完美的作品。然而,在快速瀏覽代碼中,有這樣的「for(int z = 7; z> = 0; z - ){}」,這看起來完全沒有任何作用。但是,如果我刪除或註釋掉我的程序決定任何輸入不是二進制數字。如果有人可以告訴我爲什麼需要這個循環和/或如何刪除它,它將不勝感激。謝謝:)

+1

怎麼樣使用調試器先通過,檢查實際發生了什麼。 – 2014-09-06 16:24:35

+1

您似乎認爲'數字'數組在字符串結束後將全部爲零,但只有緊跟在字符串後面的一個字符將被設置爲零。試着初始化你的數組:'char numbers [8] = {}'。 – 2014-09-06 16:26:25

+0

不同階段的打印變量在這種情況下通常也很有用。你說得對,該行不應該做任何事情,這意味着更微妙的事情正在發生。看看這段代碼,我的錢是在一個緩衝區溢出(終止空字節?) – Dave 2014-09-06 16:27:25

回答

3

在你的循環在這裏:

for (int i = 0, x = 7; x >= 0; x--, i++){ 
    if (numbers[x] <= 0){ // reads numbers[7] the first time around, but 
          // what if numbers[7] hasn't been set? 
     i--; 
    } 

你可能讀未初始化的值,如果輸入的是長不到七個字符。這是因爲numbers數組未被初始化,並且cin.get僅在字符串中的最後一個字符之後放置一個空終止符,而不是整個數組的其餘部分。一個簡單的方法來解決它是初始化您的數組:

char numbers[8] = {}; 

至於爲什麼外來循環修復它 - 讀未初始化值是不確定的行爲,這意味着有沒有關於該計劃將做什麼保證。