题解 | #浮点数加法#

浮点数加法

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

用字符串来处理就好了,把两个字符串小数点后长度对齐,再从后往前加;然后用栈处理反向输出,写于2024.3.23

#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;

int main()
{
    int i, j;
    string a, b;
    stack<char> my_stack;
    cin >> a >> b;
    int len1 = a.size();
    int len2 = b.size();
    int dot1_pos = a.find(".");
    int dot2_pos = b.find(".");
    // cout << len1 - dot1_pos - 1 << endl;
    int dot1_lens = len1 - dot1_pos - 1; // 小数点后的位数
    int dot2_lens = len2 - dot2_pos - 1;
    // cout << dot1_lens << "hdu" << dot2_lens << endl;
    // cout << dot1_lens - max(dot1_lens, dot2_lens) << endl;
    for (i = 0; i < max(dot1_lens, dot2_lens) - dot1_lens; i++) // 末尾补0,让位数对齐
    {
        a.insert(len1, "0");
    }
    for (i = 0; i < max(dot1_lens, dot2_lens) - dot2_lens; i++)
    {
        b.insert(len2, "0");
    }
    // cout << a << "hdu" << b << endl;
    int jinwei = 0;
    int zancun;
    i = a.size() - 1;
    j = b.size() - 1;
    while (i >= 0 && j >= 0)
    {
        if (a[i] != '.')
        {
            zancun = (a[i] - '0') + (b[j] - '0') + jinwei;
            jinwei = 0;
            if (zancun >= 10)
            {
                jinwei = 1;
                zancun -= 10;
            }
            my_stack.push(zancun + '0');
        }
        else
            my_stack.push('.');
        i--;
        j--;
    }
    // cout << i;
    while (i >= 0)
    {
        zancun = (a[i] - '0') + jinwei;
        jinwei = 0;
        if (zancun >= 10)
        {
            jinwei = 1;
            zancun -= 10;
        }
        my_stack.push(zancun + '0');
        i--;
    }
    while (j >= 0)
    {
        zancun = (b[j] - '0') + jinwei;
        jinwei = 0;
        if (zancun >= 10)
        {
            jinwei = 1;
            zancun -= 10;
        }
        my_stack.push(zancun + '0');
        j--;
    }
    if (jinwei == 1)
        my_stack.push('1');
    while (!my_stack.empty())
    {
        cout << my_stack.top();
        my_stack.pop();
    }

    return 0;
}

全部评论

相关推荐

04-06 16:59
已编辑
河南工业大学 Java
牛牛牛的牛子:最好扔了,实在没有选择的选择
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务