[問題] vc++ string subscript out of range

看板C_and_CPP (C/C++)作者 (coal)時間13年前 (2012/08/18 23:22), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
開發平台(Platform): VC++ 錯誤結果(Wrong Output): "string subscript out of range" 出錯的地方在 輸出 124 和 123 之間的while 輸入 100000 和 100 問題: 大數相乘 input: string a,b 相乘後輸出 答案(string p) 程式碼(Code): #include<iostream> #include<string> using namespace std; int main() { string a; string b; string p = "p"; cin>>a>>b; //減掉'0'以便計算 for( int i = 0; i < a.length(); i++ ){ a[i] = a[i] - '0'; b[i] = b[i] - '0'; } //這邊純粹DEBUG用而已 cout<<"124"<<endl; cout<<a.length()<<" "<<b.length()<<endl; //這里莫名出錯 輸入 100000 和 100 只會印出3次P的長度就當 while( p.length() < a.length() + b.length() ){ cout<<p.length()<<endl; p += "0"; } cout<<"123"<<endl; for( int i = 0; i < p.length(); i++ ) p[i] = 0; //計算部分(照我朋友寫法寫的 他的似乎是對的) for( int i = a.length() - 1; 0 <= i; i-- ){ for( int j = b.length() - 1; 0 <= j; j-- ){ p[ i+j+1 ] += a[j] * b[i]; if( p[ i+j+1 ] >= 10 ){ p[ i+j ] += p[ i+j+1 ]/10; p[ i+j+1 ] = p[ i+j+1 ]%10; } } } //印出答案 for( int i = 0 ; i < p.length(); i++ ){ if( i == 0 && p[ i ] == 0 ) continue; cout<<(int)p[i]; } cout<<endl; system("PAUSE"); return 0; } 補充: 有時後輸入一些奇怪的值他就可以跑 有時候就會當掉 小一點的數字就會正常 到底怎麼了= =?? 希望有高手可以解答 我朋友也是這樣寫...他只是把處理call reference 弄成function而已.... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.44.211.104 ※ 編輯: coal511464 來自: 114.44.211.104 (08/18 23:27)

08/19 00:47, , 1F
減掉0那邊,a跟b位數不同要分開算吧?
08/19 00:47, 1F

08/19 06:20, , 2F
哦哦 又耍笨了@@
08/19 06:20, 2F

08/19 07:37, , 3F
- '0'那邊的迴圈 用a.length()的關係?
08/19 07:37, 3F
文章代碼(AID): #1GBxCuxE (C_and_CPP)
文章代碼(AID): #1GBxCuxE (C_and_CPP)