這個循環應該添加兩個數字,它們按照各自的數字存儲在向量中。因此,例如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
}
任何幫助,非常感謝。謝謝!
當索引爲0時,'leftc.at(index-1)'你在索引-1這裏 – 2012-03-04 08:43:51
不要忘記,由於'index'是無符號的,所以'index> = 0'始終爲真。你的編譯器可能應該發出警告。 – 2012-03-04 08:46:51
@MichaelBurr好的,在這種情況下,index-1將會是MAX_VALUE(size_t)〜2^32-1,這肯定超出範圍 – 2012-03-04 08:49:04