2013-06-25 37 views
0

我有一個C++代碼,它將2位八進制數轉換爲二進制數。對於代碼的測試有效性我用了幾個在線轉換的網站,如八進制到二進制轉換混淆

thisthis

當我輸入58或爲一個八進制值,它說無效的八進制值59,但是當我在我的代碼輸入58它給二進制數爲 - 101000.再次測試我輸入101000作爲二進制數在上面的網站的計算器,然後他們給我的結果50爲八進制值。

我需要一些解釋爲什麼這樣。

這裏是C++代碼 -

#include <iostream.h> 
#include <conio.h> 
void octobin(int); 

void main() 
{ 
    clrscr(); 
    int a; 
    cout << "Enter a 2-digit octal number : "; 
    cin>>a; 
    octobin(a); 
    getch(); 
} 
void octobin(int oct) 
{ 
    long bnum=0; 
    int A[6]; 
    //Each octal digit is converted into 3 bits, 2 octal digits = 6 bits. 
    int a1,a2,quo,rem; 
    a2=oct/10; 
    a1=oct-a2*10; 
    for(int x=0;x<6;x++) 
    { 
     A[x]=0; 
    } 
    //Storing the remainders of the one's octal digit in the array. 
    for (x=0;x<3;x++) 
    { 
     quo=a1/2; 
     rem=a1%2; 
     A[x]=rem; 
     a1=quo; 
    } 
    //Storing the remainders of the ten's octal digit in the array. 
    for(x=3;x<6;x++) 
    { 
     quo=a2/2; 
     rem=a2%2; 
     A[x]=rem; 
     a2=quo; 
    } 
    //Obtaining the binary number from the remainders. 
    for(x=x-1;x>=0;x--) 
    { 
     bnum*=10; 
     bnum+=A[x]; 
    } 
    cout << "The binary number for the octal number " << oct << " is " << bnum << "." << endl; 
} 
+0

'void main'不是'main'的有效簽名。使用'int main'。 – chris

+0

'clrscr'不是標準的C或C++函數。爲什麼每次都需要清除屏幕(它會清除以前可能對解決問題有用的數據)? –

回答

3

八進制數字的數字都在[0,7]範圍內。因此,5859而不是八進制數,應該預計您的方法會給出錯誤的結果。

58評估爲101000的原因是因爲八進制數的第一個數字擴展爲二進制數的前三位。 5 = 101_2。第二部分同樣的故事,但8 = 1000_2,所以你只能得到000部分。

另一種解釋是,8 = 0 (mod 8)(我使用congruency這裏=號),這樣既80會使用你的代碼評估來000二進制。

最好的解決方案是做一些輸入驗證。例如,轉換時可以檢查以確保數字在範圍內[0,7]

0

不能使用58或59作爲輸入值。對於基督的緣故,它是八進制的。

有效位數從0到7(含)。

0

58和59不是有效的八進制值確實......你可以使用的最大位數是yourbase-1:

十進制=>基= 10 =>從0噸9

十六進制數字=>基= 16 =>數字從0到15(很好,0至F)

八路=>基= 0 8 =>位數至7

0

如果你在基座8的編碼數,沒有一個八位字節可以是8或更大。如果你打算按八位字節來完成八位字節的編碼,那麼需要進行測試以確定八位字節是8還是9,並且發出錯誤。現在你的代碼不檢查這個,所以8和9溢出到10.

相關問題