1 #include <cstdio> 2 #include <string> 3 4 string sum(string s1,string s2) 5 { 6 if(s1.length()<s2.length()) 7 { 8 string temp=s1; 9 s1=s2; 10 s2=temp; 11 } 12 int i,j; 13 for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) 14 { 15 s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0)); //注意细节 16 if(s1[i]-'0'>=10) 17 { 18 s1[i]=char((s1[i]-'0')%10+'0'); 19 if(i) s1[i-1]++; 20 else s1='1'+s1; 21 } 22 } 23 return s1; 24 } 25 26 string real_sum(string s1,string s2) 27 { 28 string::size_type idx_s1_point = s1.find("."); 29 s1.erase(idx_s1_point,1); 30 31 string::size_type idx_s2_point = s2.find("."); 32 s2.erase(idx_s2_point,1); 33 34 string::size_type int_res_len = idx_s1_point>idx_s2_point?idx_s1_point:idx_s2_point; 35 36 string::size_type dec_s1_len = s1.size() - idx_s1_point; 37 string::size_type dec_s2_len = s2.size() - idx_s2_point; 38 39 40 41 string::size_type dec_res_len; 42 if(dec_s1_len < dec_s2_len) 43 { 44 s1 += string(dec_s2_len - dec_s1_len, '0'); 45 dec_res_len = dec_s2_len; 46 } 47 else 48 { 49 s2 += string(dec_s1_len - dec_s2_len, '0'); 50 dec_res_len = dec_s1_len; 51 } 52 53 string res = sum(s1,s2); 54 55 if(res.size() > int_res_len + dec_res_len) 56 { 57 ++int_res_len; 58 } 59 60 string::size_type idx_res_tail = res.find_last_not_of("0"); 61 62 res = res.substr(0,idx_res_tail + 1); 63 res.insert(int_res_len,"."); 64 65 return res; 66 }