题解 | 浮点数加法

#include<iostream>
#include<string>

using namespace std;
int flag = 0;
string add1(string x, string y) { //先算小数
    string ans1;
    string t1;
    if (x.size() < y.size()) {
        t1 = y;
        y = x;
        x = t1;
    }
    for (int i = y.size(); i < x.size(); i++)
        ans1 = ans1 + x[i];
    int c1 = 0;
    for (int i = y.size() - 1; i >= 0; i--) {
        int cu = (x[i] - '0') + (y[i] - '0') + c1;
        char tt = cu % 10 + '0';
        ans1 = tt + ans1;
        c1 = cu / 10;
    }
    if (c1 != 0)flag = 1;
    return ans1;
}
string add2(string x1, string y1) { //再算整数
    string ans2;
    string t2;
    if (x1.size() < y1.size()) { //y1较短
        t2 = y1;
        y1 = x1;
        x1 = t2;
    }
    int c1 = 0, j = x1.size() - 1;
    for (int i = y1.size() - 1; i >= 0; i--, j--) {
        int cu = (x1[j] - '0') + (y1[i] - '0') + c1;
        char tt = cu % 10 + '0';
        ans2 = tt + ans2;
        c1 = cu / 10;
    }
    for (int i = j; i >= 0; i--) {
        int cu = (x1[i] - '0') + c1;
        char tt = cu % 10 + '0';
        ans2 = tt + ans2;
        c1 = cu / 10;
    }
    if (c1 != 0)ans2 = "1" + ans2;
    return ans2;
}
int main() {
    string a, b;
    cin >> a >> b;
    string s1, s2;
    string str1, str2;
    int c = a.find('.'), d = b.find('.');
    for (int i = 0; i < c; i++)
        s1 += a[i];
    for (int i = 0; i < d; i++)
        s2 += b[i];
    for (int i = c + 1; i < a.size(); i++)
        str1 += a[i];
    for (int i = d + 1; i < b.size(); i++)
        str2 += b[i];
    string tmp = add1(str1, str2);
    string ans = add2(s1, s2);
    if (flag == 1)ans = add2(ans, "1");
    ans = ans + "." + tmp;
    cout << ans << endl;

}

全部评论

相关推荐

qz鹿:*** 祝他毕业就失业
点赞 评论 收藏
分享
2024-11-26 15:41
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务