2014-09-27 68 views
-2

Hi new to posting but a long time follower。我一直在做一個項目,現在已經有一段時間了,我不知道如何在鏈表中實現兩個二進制數字的減法運算符。該程序將採取一個整數,並將其轉換爲二進制,然後加,減,乘二進制數然後返回結果。扣除鏈接列表中的二進制數字C++

所以我有加法運算完成後,(這工作正常只是想證明我是怎麼做的我的主要CPP)

此外

Binary operator+(const Binary &b1, const Binary &b2){ 
Binary newBinary = Binary(); 
unsigned iMax = b1.get_degree(); 
if (iMax < b2.get_degree()){ 
    iMax = b2.get_degree(); 
} 
//carry bit 
unsigned bCarry = 0; 
//traverse the list for each bit b1 and b2, highest degree 
for (unsigned i = 0; i <= iMax; ++i){ 
    unsigned sum = b1.get_bit(i) + b2.get_bit(i) + bCarry; 

    //determine if there is new carry 
    if (sum >= 2){ 
     bCarry = 1; 
     sum -= 2; 
    } 
    else bCarry = 0; 
    if (1 == sum){ 
     newBinary.set_bit(1, i); 
    } 
} 
//handle extra carry bit  
if (1 == bCarry){ 
    newBinary.set_bit(1, iMax + 1); 
    return newBinary; 
} 

}

加建工程罰款,我試圖採取什麼除了做,並將其應用於減法操作員,但我繼續打牆lol

減法:

Binary operator-(const Binary &b1, const Binary &b2){ 
Binary newBinary = Binary(); 
unsigned iMax = b1.get_degree(); 
Binary switchNode = Binary(); 
int cutoffBit = b1.get_degree(); 

if (iMax < b2.get_degree()){ 
    iMax = b2.get_degree(); 
} 

//swtich the bits of b2 by switching them from 0 to 1 and from 1 to 0 
//then add 1 to b2 
for (unsigned i = 0; i < cutoffBit; i++){ 
    if (b2.get_bit(i) == 0){ 
     switchNode.set_bit(1, i); 
    } 
    else if (b2.get_bit(i) == 1){ 
     switchNode.set_bit(0, i-1); 
    } 
} 

cout << switchNode; cout << "\t switchNode"; 
cout << "\n"; 
cout << b2; cout<< "\t b2"; 

unsigned bCarry = 0; 
//sub the two binary numbers. 
for (unsigned i = 0; i <= iMax; ++i){ 
    unsigned sub = b1.get_bit(i) + b2.get_bit(i); 

    if (sub >= 0){ 
     bCarry = 0; 
     sub -= 1; 
    } 
    else bCarry = 1; 
    if (1 == sub){ 
     switchNode.set_bit(1, i); 
    } 
} 
//handles the drop bit 
if (1 == bCarry){ 
    switchNode.set_bit(1, iMax - 1); 
    return switchNode - 1; 
} 
cout << "\n"; 
cout << switchNode; cout << "\t switch node"; 

我試圖做一些調試和我COUTS,這樣,爲什麼那些有..所以我指明瞭正確的方向任何幫助將不勝感激!

-Jason

+0

請給出一些解釋,說明它在哪裏/如何出錯。 – 2014-09-27 01:03:43

+0

對不起,我應該有更多的信息大聲笑..它不是減法權相信..我可以把它關閉,結果它應該從提供的輸入輸出是11100 ..但我一直得到111000,即時通訊不知道如何下降關閉最後一位(像2的補碼) – Alix0r 2014-09-27 01:09:17

+0

我只是覺得我的實現都是錯誤的以及大聲笑 – Alix0r 2014-09-27 01:12:33

回答

0

你2的補碼(「翻轉位加1」)似乎並沒有做什麼它聲稱要做。例如,如果位0是1,它將嘗試設置位-1!