浮点数加法

本文介绍了一个自编的浮点数加法函数,用于解决计算中出现的长尾小数问题,通过字符串处理和高精度算法实现小学加法原理。
摘要由CSDN通过智能技术生成

浮点数有时候计算结果会出现长尾小数,例如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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值