题解 | #浮点数加法#

浮点数加法

https://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8

#include<bits/stdc++.h>

using namespace std;

//取得数字
void GetNum(string a, string &aL, string &aR) {
    bool noDot = true;
    for (int i = 0; i < a.size(); ++i) {
        if (a[i] != '.' && noDot) {
            aL.push_back(a[i]);
        } else if (a[i] == '.') {
            noDot = false;
        } else {
            aR.push_back(a[i]);
        }
    }
}

//对阶、计算
void CaculateR(string a, string b, string &c, int &carry) {
    int len = 0;
    if (a.size() > b.size()) {
        len = a.size() - b.size();
        for (int i = 0; i < len; ++i) {
            b.push_back('0');
        }
    } else {
        len = b.size() - a.size();
        for (int i = 0; i < len; ++i) {
            a.push_back('0');
        }
    }
    for (int i = a.size() - 1; i >= 0; --i) {
        int temp = a[i] + b[i] - '0' - '0' + carry;
        carry = temp / 10;
        temp = temp % 10;
        c.insert(c.begin(),temp + '0') ;
    }

}

//对阶、计算
void CaculateL(string a, string b, string &c, int &carry) {
    for (int i = a.size() - 1, j = b.size() - 1; i >= 0 && j >= 0; --i, --j) {
        int temp = a[i] + b[j] - '0' - '0' + carry;
        carry = temp / 10;
        temp = temp % 10;
        c.insert(c.begin(),temp + '0') ;
    }
    if (a.size() > b.size() ) {
        for (int i = a.size() - b.size() - 1; i >= 0; --i) {
            int temp = a[i] - '0' + carry;
            carry = temp / 10;
            temp = temp % 10;
            c.insert(c.begin(),temp + '0') ;
        }
    } else {
        for (int i = b.size() - a.size() - 1; i >= 0; --i) {
            int temp = b[i] - '0' + carry;
            carry = temp / 10;
            temp = temp % 10;
            c.insert(c.begin(),temp + '0') ;
        }
    }

}

int main() {
    //输入
    string a;
    getline(cin, a);
    string b;
    getline(cin, b);
    //取得数字
    string aL;//a小数点左边的
    string aR;//a小数点右边的
    GetNum(a, aL, aR);
    string bL;//b小数点左边的
    string bR;//b小数点右边的
    GetNum(b, bL, bR);

    //计算
    int carry = 0;
//    char cR[max(aR.size(), bR.size())];
//    char cL[max(aL.size(), bL.size())];
//    string resR = cR;
//    string resL = cL;
    string resR;
    string resL;
    CaculateR(aR, bR, resR, carry);
    CaculateL(aL, bL, resL, carry);


    printf("%s.%s\n", resL.c_str(),resR.c_str());
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:46
点赞 评论 收藏
分享
伟大的烤冷面被普调:暨大✌🏻就是强
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务