题解 | #浮点数加法#
浮点数加法
https://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8
#include <iostream> #include <cstdio> #include <string> using namespace std; int main() { char str1[101], str2[101]; while (scanf("%s%s", str1, str2) != EOF) { string string1 = str1; string string2 = str2; string ret; int length1 = string1.size() - 1; int length2 = string2.size() - 1; int point1 = string1.find('.'); int point2 = string2.find('.'); //以小数点处作为中轴线 int decade = 0; while (length1 >= 0 || length2 >= 0) { int judge1 = length1 >= 0 ? (point1 > length1 ? point1 - length1 : length1 - point1) : -1;//记录当前位距离小数点的距离 int judge2 = length2 >= 0 ? (point2 > length2 ? point2 - length2 : length2 - point2) : -1;//如果str遍历完,置负接下来不参与计算 if (judge1 < judge2) {//当字符串位数不对应时 int num = string2[length2--] - '0' + decade; int remain = num % 10; decade = num / 10; ret = char(remain + '0') + ret; } else if (judge1 > judge2) { int num = string1[length1--] - '0' + decade; int remain = num % 10; decade = num / 10; ret = char(remain + '0') + ret; } else if (judge1 == judge2 && string1[length1] != '.') {//当字符串位数对应时 int num = string1[length1--] + string2[length2--] - '0' - '0' + decade; int remain = num % 10; decade = num / 10; ret = char(remain + '0') + ret; } else if (string1[length1] == '.') { ret = '.' + ret; length1--; length2--; } } printf("%s\n", ret.c_str()); } } // 64 位输出请用 printf("%lld")
笨方法,用小数点对齐后再按位数依次相加