浮点数有时候计算结果会出现长尾小数,例如0.1+0.11=0.21000000000002,这种结果很麻烦。用包装类就可以轻松的解决这个问题,不过想着很久没写加法了,高精度加法也不咋写了,自己造下轮子熟悉一下算法,于是就写了个浮点数的加法,原理就是小学加法。
#include "iostream"
#include "string"using namespace std;void treat(string a, string &aInt, string &aFloat) {for (int i = 0; i < a.size(); ++i) {if (a[i] == '.') {for (int j = i + 1; j < a.size(); ++j) {aFloat += a[j];}break;}aInt += a[i];}}int pre_add(string aFloat, string bFloat, string &ans, bool isInt, int carry) {if (aFloat.size() < bFloat.size()) return pre_add(bFloat, aFloat, ans, isInt, carry);// 假设a的小数位长int cnt = aFloat.size() - bFloat.size();for (int i = 0; i < cnt; i++) {// 补零对齐if (!isInt) {bFloat += "0";} else bFloat = "0" + bFloat;}
// cout << bFloat << endl;
// int carry = 0;int sum = 0;int len = aFloat.size();int f[len];for (int i = len - 1; i >= 0; i--) {int m = aFloat[i] - '0';int n = bFloat[i] - '0';sum = (m + n + carry) % 10;carry = (m + n + carry) / 10;f[i] = sum;}for (int i = 0; i < sizeof f / sizeof f[0]; ++i) {ans += to_string(f[i]);}return carry;
}string add(string a, string b) {string aInt = "";string aFloat = "";string bInt = "";string bFloat = "";treat(a, aInt, aFloat);treat(b, bInt, bFloat);string ans = "";int c = pre_add(aFloat, bFloat, ans, false, 0);string f = "." + ans;ans = "";c = pre_add(aInt, bInt, ans, true, c);if (c > 0) ans = "1" + ans;
// cout << ans << f;ans += f;return ans;
}int main() {
// string ans = add("0.11", "0.1");string ans = add("99999.9999", "123122222222.22222222");cout << ans;return 0;
}