题解 | #浮点数加法#
浮点数加法
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; }