方法:這裡用了資料結構棧,實際上棧更方便實現高精度加法。
步驟:1、第一個資料加數按輸入順序(高位到低位)入棧1。此時棧頂為最低位
2、第二個資料加數按輸入順序(高位到低位)入棧2。此時棧頂為最低位
3、將棧1、棧2均pop出棧頂做加法,並考慮進位,結果入棧3,這時棧3正好是低位入棧。
4、處理多餘的棧1、棧2。
5、直接pop出棧3,即正好的從高位到低位的結果。
完整的實現代碼如下:
#include "iostream"#include "stack"using namespace std;stack<int>s1;stack<int>s2;stack<int>s3;char c1[100];char c2[100];int main(void){printf("請輸入第一個加數:");cin>>c1;printf("請輸入第二個加數:");cin>>c2;int len1=strlen(c1);int len2=strlen(c2);for(int i=0;i<len1;i++){s1.push(c1[i]-'0'); //按輸入順序(高位到低位)入棧1,此時棧頂為最低位}for(int i=0;i<len2;i++){s2.push(c2[i]-'0'); //按輸入順序(高位到低位)入棧2,此時棧頂為最低位}int tmp=0;while(!s1.empty() && !s2.empty()){tmp += s1.top()+s2.top(); // 將棧1、棧2均pop出棧頂做加法,並考慮進位,結果入棧3,這時棧3正好是低位入棧s1.pop();s2.pop();s3.push(tmp%10);tmp = tmp/10;}while(!s1.empty()) //處理多餘的棧1{tmp += s1.top();s1.pop();s3.push(tmp%10);tmp = tmp/10;}while(!s2.empty()) //處理多餘的棧2{tmp += s2.top();s2.pop();s3.push(tmp%10);tmp = tmp/10;}if(tmp) //處理多餘的進位{s3.push(tmp);}printf("兩個數相加的結果為:");while(!s3.empty()) //直接pop出棧3,即正好的從高位到低位的結果{cout<<s3.top();s3.pop();}cout<<endl;system("pause");return 0;}
運行如下: