整数和浮点数加法

Posted randyniu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了整数和浮点数加法相关的知识,希望对你有一定的参考价值。

//本来想着将浮点数分成两部分,然后进行整数加法,唉 还是算了,太麻烦了,下面这样写就是冗余了很多。
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; }

 



以上是关于整数和浮点数加法的主要内容,如果未能解决你的问题,请参考以下文章

SSE 整数与浮点数练习

整数和浮点数

Python中整数和浮点数

Python中整数和浮点数

Python中整数和浮点数

整数和浮点数转换