整數和浮點數加法
阿新 • • 發佈:2018-09-02
浮點數 bsp class col ++ diff turn clas -i
//本來想著將浮點數分成兩部分,然後進行整數加法,唉 還是算了,太麻煩了,下面這樣寫就是冗余了很多。
string floatAdd(string &s1, string &s2) { int idx1 = s1.find(‘.‘); int idx2 = s2.find(‘.‘); int len1 = s1.size(); int len2 = s2.size(); int beforePoint = max(idx1, idx2); int afterPoint = max(len1-1-idx1, len2-1-idx2);char arr[beforePoint + afterPoint + 1 + 1 + 1] = {0}; int diff = 0; int i = len1 - 1; int j = len2 - 1; int idx = beforePoint + afterPoint + 1; int jinwei = 0; int add = 0; if(len1-1-idx1 >= len2-1-idx2) { diff = len1-idx1-len2+idx2; while(diff>0) { arr[idx--] = s1[i--]; diff--; } while(j > idx2) { add = s1[i]-‘0‘ + s2[j]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --i; --j; } } else { diff = len2-idx2-len1+idx1;while(diff>0) { arr[idx--] = s2[j--]; diff--; } while(i > idx1) { add = s1[i]-‘0‘ + s2[j]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --i; --j; } } arr[idx--] = ‘.‘; i--; j--; if(idx1 >= idx2) { while(j>=0) { add = s1[i]-‘0‘ + s2[j]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --i; --j; } while(i>=0) { add = s1[i]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --i; } } else { while(i>=0) { add = s1[i]-‘0‘ + s2[j]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --i; --j; } while(j>=0) { add = s2[j]-‘0‘ + jinwei; arr[idx--] = add%10+‘0‘; jinwei = add/10; --j; } } if(jinwei) arr[0] = ‘1‘; else arr[0] = ‘0‘; for(int i=0; i<=beforePoint + afterPoint + 1; ++i) cout << arr[i]; cout << endl; string result = arr; result = result[0] == ‘0‘ ? result.substr(1) : result; return result; } int main() { string s1 = "1111.1111"; string s2 = "1111.1111"; cout << floatAdd(s2, s1) << endl; }
//這個是整數加法 也還是挺簡單的,
string intAdd_aux(string &s1, string &s2) { int i= s1.size()-1; int j= s2.size()-1; string result; int add = 0; int jinwei = 0; while(j>=0) { add = s1[i] - ‘0‘ + s2[j]-‘0‘ + jinwei; result = (char)(add%10+‘0‘)+result ; jinwei = add/10; --i; --j; } add = 0; while(i>=0) { add = s1[i] - ‘0‘ + jinwei; result = (char)(add%10+‘0‘)+result ; jinwei = add/10; --i; } return result; } string intAdd(string &s1, string &s2) { int len1 = s1.size(); int len2 = s2.size(); string result; if(len1 >= len2) { result = intAdd_aux(s1, s2); } else { result = intAdd_aux(s2, s1); } return result; }
整數和浮點數加法