2012-03-04 98 views
0

這個循環應該添加兩個數字,它們按照各自的數字存儲在向量中。因此,例如leftc將包含[10] {0,9,0,0,0,0,0,0,5,7},並且rightc將包含 [10] {0,0,0,0,0, 0,0,0,9,6}並且在循環末尾number應該包含「0900000153」(在程序的後面剝去前導零)。它工作完美,直到它達到索引= 0,然後它會導致溢出錯誤,但我不明白爲什麼。爲什麼此循環導致溢出錯誤?

string number;              // accumulates the result of the addition 
int num;               // holds the result of adding corresponding elements 
short carry = 1; 

for (size_t index = leftc.size() - 1; index >= 0; index--)  // start from the end of the vectors and work toward the beginning 
{ 
    num = leftc.at(index) + rightc.at(index);      // add the two elements and store in num 
    if (num >= 10) 
    { 
     num %= 10; 
     leftc.at(index - 1) += carry; 
    } 
    num += '0';              // convert num from int to char            
    number.insert(number.begin(), num);       // store num at front of number 
} 

任何幫助,非常感謝。謝謝!

+2

當索引爲0時,'leftc.at(index-1)'你在索引-1這裏 – 2012-03-04 08:43:51

+0

不要忘記,由於'index'是無符號的,所以'index> = 0'始終爲真。你的編譯器可能應該發出警告。 – 2012-03-04 08:46:51

+0

@MichaelBurr好的,在這種情況下,index-1將會是MAX_VALUE(size_t)〜2^32-1,這肯定超出範圍 – 2012-03-04 08:49:04

回答

3

你在這裏

for (size_t index = leftc.size() - 1; index >= 0; index--) 

由於size_t的一個問題是無符號,index總是>=0

+0

這解決了它!我從來不會猜到......非常感謝! – JamesGold 2012-03-04 08:58:51

1

當您的index爲0時,您的(index-1)將爲-1 ...因此它會發生溢出錯誤...因爲您嘗試訪問索引爲「-1」的項目。

0
if (num >= 10) 
{ 
    num %= 10; 
    leftc.at(index - 1) += carry; 
} 

在這裏你會得到一個錯誤,如果索引爲零 - 你訪問第(-1)個元素。

相關問題