2016-03-04 65 views
0

所以,這裏是我的代碼: http://pastebin.com/MejYmpvK位集合印刷用C

我想要得到的輸出顯示此:

The BitSet is: 
0000000001001010 

Modified BitSet at index '14' = '1' is: 
0010000001001010 

The value at index '14' is: 
1 

Modified Bitset at index '14' = '0' is: 
0000000001001010 

The value at index '14' is: 
0 

但是,它給我這個輸出,而不是:

The BitSet is: 
0000000001001010 

Modified BitSet at index '14' = '1' is: 
0010000001001010 

The value at index '14' is: 
0 

Modified Bitset at index '14' = '0' is: 
0000000001001010 

The value at index '14' is: 
0 

除顯示方法外,一切都正常工作。不知道是怎麼回事(整個代碼是在上面的引擎收錄鏈接):設置後位

/* Returns the value of the bit at 'index' */ 
int bitValue(bitSet bs, int index){ 

    /* Shifts right to the passed index value */ 
    int value = ((bs & (int)pow(power, index)) >> index); 

    return value; 
} 
+3

歡迎來到Stack Overflow!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

+0

看起來你期望在索引14處實際上是索引13(索引從0開始)。請參閱https://en.wikipedia.org/wiki/Off-by-one_error – martinkunev

+0

您在設置位14後忘記更新'值',所以當然它會打印舊值。你需要再次調用'bitValue'來獲得新的值。你的局部變量'value'本身不會奇蹟般地改變,對吧? –

回答

0

你的主要功能是沒有更新的價值。嘗試這個;

int main() { 
    bitSet bits = makeBitSet(); 
    int value = bitValue(bits, 14); 

    printf("The BitSet is: \n"); 
    displayBitSet(bits); 
    printf("\n\nModified BitSet at index '14' = '1' is: \n"); 
    setBit(&bits, 14); 
    displayBitSet(bits); 
    printf("\n\nThe value at index '14' is: \n"); 
    value = bitValue(bits, 14); 
    printf("%d", value); 
    printf("\n\nModified BitSet at index '14' = '0' is: \n"); 
    clearBit(&bits, 14); 
    displayBitSet(bits); 
    printf("\n\nThe value at index '14' is: \n"); 
    value = bitValue(bits, 14); 
    printf("%d\n", value); 

    return (0); 
} 
+0

謝謝!甚至沒有意識到這一點。多麼小的一個愚蠢的錯誤。 – Team42